Learn Blazor · 13/15

State Management Strategies

7 min read

Welcome to the memory center of your application! 🧠

Imagine you are running a busy restaurant (your app). You have a waiter (Component A) taking an order, and a chef (Component B) cooking it. If the waiter writes the order on a napkin and keeps it in their pocket, the chef has no idea what to cook. The kitchen catches fire, and customers leave.

You need a central "Ticket Rail" or a shared whiteboard where everyone can see the current state of orders. That is State Management.

In Blazor, "State" is simply the data your application is holding onto at any given moment—user preferences, the items in a shopping cart, or the current user's profile. Without a strategy, your components act like strangers who refuse to talk to each other.

Let's fix that.


1. Simple State Containers using Injected Services

The Problem

You have a ProductList component and a Cart component. When you click "Add to Cart" in the list, the Cart component needs to know about it. Passing parameters from Parent → Child → Grandchild → Great-Grandchild is called "Parameter Drilling," and it is absolutely miserable to maintain.

The Solution: The "Shared Service"

Instead of passing data down a chain, we create a specific C# class (a container) to hold the data, and we inject that same instance into every component that needs it.

Real Life Analogy: Instead of whispering a secret through a line of 10 people (Telephone game), you write the secret on a whiteboard in the hallway. Anyone who needs to know just walks out and looks at the whiteboard.

Implementation

We use Dependency Injection (DI).

Step 1: Create the State Container

Create a simple class. Not a component, just a class.

csharp
public class CartState
{
    // The actual data
    public List<string> SelectedItems { get; private set; } = new();

    public void AddItem(string item)
    {
        SelectedItems.Add(item);
        // We will add notification logic here later!
        Console.WriteLine($"{item} added. Total: {SelectedItems.Count}");
    }
}

Step 2: Register the Service

In Program.cs, we register this service.

⚠️ Industry Standard: Use Scoped for user-specific data (like a shopping cart).

  • Transient: New copy every time you ask. (Bad for state).
  • Scoped: Created once per user connection/circuit. (Perfect for state).
  • Singleton: Created once for the entire server. (If you use this for a shopping cart, User A will see User B's pizza! Only use Singleton for global config).
csharp
// Program.cs
builder.Services.AddScoped<CartState>();

Step 3: Inject and Use

Now, any component can access the same list.

razor
@inject CartState Cart

<button @onclick="() => Cart.AddItem(@PizzaName)">Add Pizza</button>

<p>Items in cart: @Cart.SelectedItems.Count</p>

@code {
    public string PizzaName = "Pepperoni";
}

2. The Observer Pattern: Notifying Components of State Changes

The Problem

If you run the code above, you’ll notice something funny. You click the button, Console.WriteLine says the item was added... but the <p> tag still says "Items in cart: 0".

Why? Because Blazor components are lazy. They only re-render when they are triggered directly. They don't monitor your C# classes for changes automatically. The whiteboard changed, but the chef is looking out the window.

The Solution: Events (The Observer Pattern)

We need the service to ring a bell 🔔 whenever data changes. Components will "subscribe" to that bell.

Implementation

Step 1: Update the State Container

We add a C# Action (event) that happens when items change.

csharp
public class CartState
{
    public List<string> SelectedItems { get; private set; } = new();

    // The "Bell"
    public event Action? OnChange;

    public void AddItem(string item)
    {
        SelectedItems.Add(item);
        NotifyStateChanged();
    }

    private void NotifyStateChanged() => OnChange?.Invoke();
}

Step 2: Subscribe in the Component

The component needs to tell Blazor: "When this event fires, re-render me."

⚠️ Critical Industry Practice: You must unsubscribe (dispose) from events when the component is destroyed. If you don't, the State Container keeps a reference to the dead component, causing a Memory Leak. Your server's RAM will eventually explode, and your boss will be sad.

razor
@implements IDisposable
@inject CartState Cart

<h3>My Cart (@Cart.SelectedItems.Count)</h3>

@code {
    protected override void OnInitialized()
    {
        // Subscribe to the bell
        Cart.OnChange += StateHasChanged;
    }

    public void Dispose()
    {
        // Unsubscribe to prevent memory leaks! 🛑
        Cart.OnChange -= StateHasChanged;
    }
}

Now, when you click "Add" in one component, the "My Cart" header in a completely different component updates instantly. Magic. ✨


3. Preserving Component State During Prerendering

The Problem

If you are using Blazor Web Apps (.NET 8+) or Blazor Server with prerendering enabled, your app actually starts twice.

  1. Server Prerender: The server generates HTML instantly (for SEO and perceived speed).
  2. Client Hydration: The browser connects via SignalR (or WASM) and the app starts "for real."

If your initialization logic fetches data from a database, it fetches it twice. Even worse, the UI might flicker:

  • Flash 1 (Prerender): Data Loaded.
  • Flash 2 (Client Connects): Data Reset (Blank).
  • Flash 3 (Client Fetch): Data Loaded again.

The Solution: PersistentComponentState

We need to pack the data into the HTML during the prerender so the client can unpack it immediately instead of fetching it again. Think of it as packing a lunch for the component so it doesn't have to go to the store when it arrives at work. 🍱

Implementation

You need to inject PersistentComponentState.

razor
@implements IDisposable
@inject PersistentComponentState ApplicationState
@inject IWeatherDataService WeatherService

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <!-- Display forecasts -->
}

@code {
    private WeatherForecast[]? forecasts;
    private PersistingComponentStateSubscription persistingSubscription;

    protected override async Task OnInitializedAsync()
    {
        // 1. Try to load from the "packed lunch" (persisted state)
        persistingSubscription = ApplicationState.RegisterOnPersisting(PersistData);

        if (!ApplicationState.TryTakeFromJson<WeatherForecast[]>("fetchdata", out var restored))
        {
            // 2. If no packed lunch, go to the store (database)
            forecasts = await WeatherService.GetForecastAsync(DateOnly.FromDateTime(DateTime.Now));
        }
        else
        {
            // 3. Eat the lunch
            forecasts = restored;
        }
    }

    // This runs right before the Prerender finishes
    private Task PersistData()
    {
        ApplicationState.PersistAsJson("fetchdata", forecasts);
        return Task.CompletedTask;
    }

    public void Dispose()
    {
        persistingSubscription.Dispose();
    }
}

This eliminates the "double fetch" and the "UI flicker." It makes your app feel incredibly solid and professional.


4. Introduction to Flux/Redux Patterns in Blazor

The Problem

As your app grows to Enterprise size, having 50 different Services injecting into each other creates "Spaghetti State." You lose track of who changed the data. Did the UserProfile component change the theme, or did the Settings component do it?

The Solution: Unidirectional Data Flow (Flux/Redux)

Instead of Components changing data directly, they ask a Dispatcher to do it.

The Flow:

  1. View (Component): "I want to Increment Counter." (Dispatches an Action)
  2. Dispatcher: "I hear an Increment Action." (Sends to Reducer)
  3. Reducer: "Current count is 0. Action is Increment. New count is 1." (Updates Store)
  4. Store: "I have changed." (Notifies View)

It sounds complex, but it makes debugging massive apps easy because data only flows one way.

Industry Standard: Fluxor

Do not write your own Redux implementation unless you are doing it for fun. In the .NET world, the library Fluxor is the gold standard for this.

Concept Example (Mental Model):

  1. The Store: Holds { Count: 0 }. It is read-only.
  2. The Action: A simple class public class IncrementCounterAction {}.
  3. The Reducer: Pure method.
    csharp
    [ReducerMethod]
    public static CounterState ReduceIncrement(CounterState state, IncrementCounterAction action)
    {
        return new CounterState(clickCount: state.ClickCount + 1);
    }

Why use it?
If you have a bug where the counter jumps by 10 instead of 1, you don't search through 50 Razor files. You look at the one Reducer method. It acts as a strict gatekeeper for your data.


🧠 Fun Fact

Managing state in Blazor Server is technically easier than React or Angular because the state lives on the server memory. You don't always need to serialize JSON back and forth. But remember: Server memory is expensive. Don't store 10MB of data per user in a Scoped service, or your server will crash when 100 users log in!

🔗 Useful Resources

Keep your state clean, and your users happy! 🍕

Challenge

You are tasked with implementing a shared shopping cart state for a Blazor application using an injected service and the observer pattern. You will create a state container, CartState, and two components, ProductDisplay and CartSummary, that interact with it.

Requirements:

  1. CartState.cs:

    • Create a class named CartState.
    • It must contain a private list to hold Product objects.
    • Implement a public method AddItem(Product product) which adds a product to the list.
    • Implement a public method GetItemCount() which returns the total number of items.
    • Implement the observer pattern:
      • Declare a public event Action? OnChange;
      • Create a private method NotifyStateChanged() that invokes the OnChange event.
      • Call NotifyStateChanged() from within the AddItem method.
  2. ProductDisplay.razor:

    • Inject the CartState service.
    • Wire the "Add to Cart" button's @onclick event to a method.
    • This method should call the CartState.AddItem method, passing in the featuredProduct.
  3. CartSummary.razor:

    • Inject the CartState service.
    • Implement the IDisposable interface.
    • In the OnInitialized lifecycle method, subscribe a handler to the CartState.OnChange event. This handler should update the itemCount by calling CartState.GetItemCount() and then call StateHasChanged() to trigger a UI re-render.
    • In the Dispose method, unsubscribe from the CartState.OnChange event to prevent memory leaks.

Expected result

Your final code should consist of three completed parts: the CartState service and the two Razor components. The implementation should ensure that when the button in ProductDisplay is clicked, the item count in CartSummary updates automatically.

CartState.cs

A complete implementation of the state container with a private list, public methods, and an event for notifications.

csharp
using System;
using System.Collections.Generic;

public class CartState
{
    private readonly List<Product> _items = new List<Product>();

    public event Action? OnChange;

    public void AddItem(Product product)
    {
        _items.Add(product);
        NotifyStateChanged();
    }

    public int GetItemCount() => _items.Count;

    private void NotifyStateChanged() => OnChange?.Invoke();
}

ProductDisplay.razor

This component injects the service and uses it to add an item to the cart when the button is clicked.

razor
@inject CartState CartState

<h3>Our Featured Product</h3>
<p>Blazor Pro E-book</p>
<button class="btn btn-primary" @onclick="AddToCart">Add to Cart</button>

@code {
    private Product featuredProduct = new Product { Id = 1, Name = "Blazor Pro E-book" };

    private void AddToCart()
    {
        CartState.AddItem(featuredProduct);
    }
}

CartSummary.razor

This component injects the service, implements IDisposable, and subscribes/unsubscribes to the OnChange event to keep its UI synchronized with the application state.

razor
@implements IDisposable
@inject CartState CartState

<div class="cart-summary">
    Items in cart: @itemCount
</div>

@code {
    private int itemCount = 0;

    protected override void OnInitialized()
    {
        // Subscribe to the event
        CartState.OnChange += HandleStateChange;
        // Set initial count
        itemCount = CartState.GetItemCount();
    }

    private void HandleStateChange()
    {
        itemCount = CartState.GetItemCount();
        InvokeAsync(StateHasChanged);
    }

    public void Dispose()
    {
        // Unsubscribe to prevent memory leaks
        CartState.OnChange -= HandleStateChange;
    }
}
csharp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.