State Management in Blazor

State management is crucial for building interactive and data-driven web applications. In Blazor, state refers to the data that drives your UI components.


Why Manage State?

  • Preserve user input between interactions
  • Share data across components or pages
  • Respond to user actions and update the UI

Local State in a Component

Each Blazor component can manage its own state:

@code {
    int count = 0;

    void Increment() => count++;
}
<p>Count: @count</p>
<button @onclick="Increment">+1</button>

Sharing State: Cascading Values

Use CascadingParameter to share data across components:

// App.razor
<CascadingValue Value="User">
    <MainLayout />
</CascadingValue>

@code {
    string User = "Admin";
}
// In child component
[CascadingParameter]
public string User { get; set; }

App-Wide State Using Services

Create a singleton service to store shared data:

public class AppState
{
    public string Theme { get; set; } = "light";
}

Register it in Program.cs:

builder.Services.AddSingleton<AppState>();

Inject it into components:

@inject AppState State

<p>Theme: @State.Theme</p>

Persisting State (LocalStorage)

Use JavaScript Interop or libraries like Blazored.LocalStorage to persist state:

@inject ILocalStorageService localStorage

await localStorage.SetItemAsync("theme", "dark");

var theme = await localStorage.GetItemAsync<string>("theme");

Blazor provides multiple ways to manage state, from simple component variables to shared services and local storage. In the next section, we’ll start building cross-platform applications using .NET MAUI.