Migrating from a hand-written state container
Many Blazor apps keep shared state in a service of their own: the in-memory state container of Microsoft's Blazor docs, a class with properties, methods that change them and an OnChange event that components subscribe to. On .NET 10 the same service can carry its values from prerendering into the interactive render with [PersistentState] and RegisterPersistentService.
That pattern needs no library and is often enough. This guide is for the container that has grown: several components selecting from it, loads that overlap, changes from background threads, a prerendered page that loads twice. It moves the container to a Ducky 2.0 SliceStore<TState>, which keeps the shape of the service (methods that change state) and adds a store underneath.
Every snippet on this page comes from the compiled sample in docs/migration/samples/state-container. Before uses ASP.NET Core alone, as Microsoft's docs describe it. After is the same app on Ducky 2.0, and After.Tests holds its tests and one test per behaviour change below.
Checklist
- Target
net11.0. AddDuckyandDucky.Blazor, andDucky.Testingto test projects. - Gather the container's properties into one immutable record and derive the container from
SliceStore<TState>; each method that changes state callsSet(see The container becomes a SliceStore). - Move each method that awaits a service into an effect that injects the service and the SliceStore, triggered by an action: callers of
LoadAsync()now dispatchLoadCount(see Async methods become effects). - Move the first load into an effect on
StoreInitializedthat returns early when the slice was restored (the load rule), and register the slice withPrerender<TSlice, TState>(include), whose predicate seeds only a loaded state (see Registration). - In components, inherit
DuckyComponent,SelectinOnInitialized, and delete theOnChangesubscription, theInvokeAsyncwrapper andIDisposable(see Components). In_Imports.razorand the.razorfiles that means@using Ducky,@using Ducky.Blazorand@inherits DuckyComponent;@inject CounterStorestays, and@implements IDisposablegoes. - Replace the container's
AddScopedorAddSingleton, andRegisterPersistentService, withAddDucky(see Registration). - Run the app's tests, then read Behaviour changes.
Before and after
The container becomes a SliceStore
// A hand-written state container, as in Microsoft's Blazor state management docs: properties, methods that change them,
// and an OnChange event. [PersistentState] (.NET 10) carries the prerendered values into the interactive render.
public interface ICounterApi
{
Task<int> GetCountAsync(CancellationToken cancellationToken);
}
public sealed class CounterStore(ICounterApi api)
{
[PersistentState]
public int Count { get; set; }
public bool IsLoading { get; private set; }
public string? Error { get; private set; }
public event Action? OnChange;
public void Increment(int amount)
{
Count += amount;
NotifyStateChanged();
}
public async Task LoadAsync(CancellationToken cancellationToken)
{
IsLoading = true;
Error = null;
NotifyStateChanged();
try
{
Count = await api.GetCountAsync(cancellationToken);
}
catch (HttpRequestException exception)
{
Error = exception.Message;
}
IsLoading = false;
NotifyStateChanged();
}
private void NotifyStateChanged() => OnChange?.Invoke();
}// Ducky 2.0: the container becomes a SliceStore. Its state is one immutable record, its methods keep their names, and
// each change is a Set whose mutator runs when the store reduces it: no event to raise, no lost update.
public interface ICounterApi
{
Task<int> GetCountAsync(CancellationToken cancellationToken);
}
public sealed record CounterState(int Count, bool IsLoading, string? Error);
public sealed record LoadCount; // what a component dispatches to (re)load
public sealed class CounterStore : SliceStore<CounterState>
{
public CounterStore() => On<LoadCount>(state => state with { IsLoading = true, Error = null });
public override string Key => "counter";
protected override CounterState Initial => new(Count: 0, IsLoading: false, Error: null);
public void Increment(int amount) => Set(state => state with { Count = state.Count + amount });
public void Loaded(int count) => Set(state => state with { Count = count, IsLoading = false });
public void LoadFailed(string error) => Set(state => state with { IsLoading = false, Error = error });
}Callers keep calling Increment(1). The Set mutator runs when the store reduces the change, against the latest state, so two concurrent calls can't overwrite each other, and the store notifies whoever selected a changed value. SetAsync returns a Task<DispatchResult> that completes once the change is reduced. State is a point-in-time read, not a subscription (see SliceStore).
Async methods become effects
A SliceStore has a parameterless constructor and never awaits. LoadAsync becomes an effect on a LoadCount action, which the SliceStore also reduces to set IsLoading:
// Ducky 2.0: a SliceStore never awaits. The async method becomes an effect that injects the service and the SliceStore;
// Switch cancels a running load when a newer LoadCount arrives, and the superseded run's Set calls are dropped.
public sealed class LoadCountEffect(ICounterApi api, CounterStore counter) : Effect<LoadCount>
{
public override Concurrency Policy => Concurrency.Switch;
public override async Task Handle(LoadCount action, EffectContext context, CancellationToken cancellationToken)
{
try
{
counter.Loaded(await api.GetCountAsync(cancellationToken));
}
catch (HttpRequestException exception)
{
counter.LoadFailed(exception.Message);
}
}
}
// The first load runs once, when the store is initialized, unless the prerender seed already restored the slice.
public sealed class LoadCountOnStart : Effect<StoreInitialized>
{
public override Task Handle(StoreInitialized action, EffectContext context, CancellationToken cancellationToken)
{
if (!context.State.WasRestored<CounterState>())
{
context.Dispatch(new LoadCount());
}
return Task.CompletedTask;
}
}The effect gets a cancellation token and a concurrency policy; LoadCountOnStart is the load rule, which loads once the store is initialized unless the prerender seed restored the slice. The tests let the store build the effect, so it injects the store's own CounterStore (see Testing):
[Fact]
public async Task Increment_AddsAmount()
{
await using var store = TestStore.Create(ducky => ducky.AddSlice<CounterStore>());
var counter = store.GetSlice<CounterStore>();
counter.Increment(2);
await store.Settled();
counter.State.Count.ShouldBe(2);
}
[Fact]
public async Task LoadCountEffect_ApiAnswers_SetsCount()
{
var api = new FakeCounterApi();
CounterStore? counter = null;
var running = EffectTest.Run<LoadCountEffect, LoadCount>(
new LoadCount(),
ducky => ducky.AddSlice<CounterStore>(),
store => counter = store.GetSlice<CounterStore>(),
services: s => s.AddSingleton<ICounterApi>(api));
await api.Called(0);
api.Complete(0, 42);
await running;
counter!.State.ShouldBe(new CounterState(Count: 42, IsLoading: false, Error: null));
}Components
// The component subscribes to OnChange, marshals to the renderer with InvokeAsync, and must unsubscribe on disposal.
public sealed class CounterView : ComponentBase, IDisposable
{
[Inject]
private CounterStore Store { get; set; } = null!;
public void Increment() => Store.Increment(1);
public void Dispose() => Store.OnChange -= OnStoreChanged;
protected override async Task OnInitializedAsync()
{
Store.OnChange += OnStoreChanged;
await Store.LoadAsync(CancellationToken.None);
}
protected override void BuildRenderTree(RenderTreeBuilder builder) =>
builder.AddContent(0, Store.IsLoading ? "loading" : Store.Count.ToString(CultureInfo.InvariantCulture));
// OnChange runs on the thread that changed the store: after the await, that may not be the renderer's.
private void OnStoreChanged() => _ = InvokeAsync(StateHasChanged);
}// Ducky 2.0: the component selects what it shows and calls the SliceStore's methods. DuckyComponent marshals its own
// re-render to the renderer and disposes its selections: no OnChange, no InvokeAsync, no IDisposable.
public sealed class CounterView : DuckyComponent
{
private Selection<CounterState>? _counter;
[Inject]
private CounterStore Counter { get; set; } = null!;
public void Increment() => Counter.Increment(1);
public void Refresh() => Dispatch(new LoadCount());
protected override void OnInitialized() => _counter = Select((CounterState state) => state);
protected override void BuildRenderTree(RenderTreeBuilder builder) =>
builder.AddContent(0, _counter!.Value.IsLoading ? "loading" : _counter.Value.Count.ToString(CultureInfo.InvariantCulture));
}Registration
// Scoped on the server (one per circuit); Microsoft's docs register it as a singleton in a standalone
// WebAssembly app, and as a singleton in the .Client project's Program.cs for InteractiveAuto and
// InteractiveWebAssembly. RegisterPersistentService hands its [PersistentState] properties from prerender to
// interactive.
services.AddSingleton(api);
services.AddScoped<CounterStore>();
services.AddRazorComponents()
.RegisterPersistentService<CounterStore>(RenderMode.InteractiveAuto);// Ducky 2.0: the store picks its lifetime (a singleton in the browser, scoped on the server). Prerender<T> replaces
// [PersistentState] and RegisterPersistentService: it seeds the slice once the prerender store is idle, and only a
// loaded state, so a failed prerender load is retried in the browser.
services.AddSingleton(api);
services.AddDucky(ducky => ducky
.AddDuckyGenerated_StateContainerSample_After()
.UseJson(AppJson.Default)
.Prerender<CounterStore, CounterState>(static state => state is { IsLoading: false, Error: null }));AddDuckyGenerated_{Assembly}() registers every slice, SliceStore and effect the assembly declares, and CounterStore is injectable as the store-owned instance. AppJson is a JsonSerializerContext listing CounterState: the prerender seed is serialized through it, never by reflection.
What .NET 10 persistent state covers, and where Ducky goes further
[PersistentState] on a service property, registered with RegisterPersistentService<T>(RenderMode), serializes the property during prerendering and restores it when the interactive render mode resolves the service. In a .Client project the service must be a singleton. It carries values into the interactive render, and on Blazor Server across a paused and resumed circuit; it doesn't write to browser storage, follow other tabs or coordinate async work.
| Need | .NET 10, no library | Ducky 2.0 |
|---|---|---|
| Prerendered values reach the interactive render | [PersistentState] + RegisterPersistentService (docs) |
Prerender<TSlice>(), written once the prerender store is idle (Prerender) |
| A failed prerender load is retried in the browser | your own check | the include predicate leaves the slice out of the seed |
| Serialization | System.Text.Json with default settings, not trimmer safe without preserving the types; a PersistentComponentStateSerializer<T> replaces it per type |
your JsonSerializerContext, source-generated |
| Survives a reload, per browser or per user | no (docs: "The example doesn't persist data without further development") | Persist<TSlice>(): localStorage, sessionStorage or IDistributedCache (Persistence) |
| Follows the user's other tabs | no | SyncAcrossTabs (Cross-tab sync) |
| Changes from other threads | each component wraps StateHasChanged in InvokeAsync (docs) |
Ducky's components marshal their own re-render |
| Overlapping async loads | your own cancellation | effect policies: Switch, Exhaust, Queue, Merge |
| History and time travel | no | Redux DevTools (UseDevTools()) |
Keep [PersistentState] for component state that isn't in the store.
Mapping table
| Hand-written container | Ducky 2.0 |
|---|---|
| a service class with mutable properties | a SliceStore<TState> over one immutable record |
| the initial values of the fields | protected override TState Initial |
a method that sets properties and raises OnChange |
a method that calls Set(state => state with { ... }) |
an async method that awaits a service, then sets properties |
an Effect<TAction> that injects the service and the SliceStore and calls its methods |
event Action OnChange |
nothing: selections are notified when their value changes |
OnChange += StateHasChanged in OnInitialized, -= in Dispose |
Select(...) in OnInitialized of a DuckyComponent; it disposes its selections |
InvokeAsync(StateHasChanged) for changes from other threads |
nothing: DuckyComponent marshals its re-render; your own onChange callbacks still use InvokeAsync |
a service subscriber outside components (OnChange += ...) |
store.Select(selector, onChange); dispose the Selection to unsubscribe |
AddSingleton<T>() in WebAssembly, AddScoped<T>() on the server |
AddDucky(...): the store is a singleton in the browser and scoped on the server |
[PersistentState] on service properties + RegisterPersistentService<T>(RenderMode) |
Prerender<TSlice>() |
localStorage through your own JS interop |
Persist<TSlice>() |
CascadingValueSource<T> notifications |
a Select in each consuming component |
Behaviour changes
Each comes with the test that pins it.
No lost updates
Count += amount on a plain property is a read followed by a write; two threads can read the same value and one increment is lost, unless the container takes a lock. A SliceStore's mutators run one at a time when the store reduces them, each against the latest state:
[Fact]
public async Task ConcurrentIncrements_NoneIsLost()
{
await using var store = TestStore.Create(ducky => ducky.AddSlice<CounterStore>());
var counter = store.GetSlice<CounterStore>();
// Count += amount on a plain property is a read and a write: two threads can both read 0 and both write 1.
await Task.WhenAll(Enumerable.Range(0, 8).Select(_ => Task.Run(() =>
{
for (var i = 0; i < 250; i++)
{
counter.Increment(1);
}
})));
await store.Settled();
counter.State.Count.ShouldBe(2000); // each mutator ran at reduce time, one at a time, against the latest state
}Changes from other threads need no InvokeAsync
The container raises OnChange on the thread that changed it, so each component must marshal with InvokeAsync, or Blazor throws "The current thread is not associated with the Dispatcher". DuckyComponent marshals its own re-render to the renderer:
[Fact]
public async Task ChangeFromAnotherThread_RerendersWithoutInvokeAsync()
{
var view = Render<CounterView>();
await _api.Called(0);
_api.Complete(0, 1);
await Services.GetRequiredService<IStore>().WhenIdleAsync(Xunit.TestContext.Current.CancellationToken);
view.WaitForAssertion(() => view.Markup.ShouldBe("1"));
var counter = Services.GetRequiredService<CounterStore>();
await Task.Run(() => counter.Increment(1), Xunit.TestContext.Current.CancellationToken); // a thread-pool thread
view.WaitForAssertion(() => view.Markup.ShouldBe("2")); // DuckyComponent marshalled its own re-render
}Components re-render only for the values they selected
Every OnChange subscriber re-renders on every change of the container. A Ducky component re-renders when a value it selected changed:
[Fact]
public async Task Selection_RerendersOnlyWhenTheSelectedValueChanges()
{
var badge = Render<LoadingBadge>();
await _api.Called(0);
_api.Complete(0, 1);
await Services.GetRequiredService<IStore>().WhenIdleAsync(Xunit.TestContext.Current.CancellationToken);
badge.WaitForAssertion(() => badge.Markup.ShouldBe("idle"));
var renders = badge.Instance.Renders;
await badge.InvokeAsync(() => Services.GetRequiredService<CounterStore>().Increment(5));
await Services.GetRequiredService<IStore>().WhenIdleAsync(Xunit.TestContext.Current.CancellationToken);
badge.Instance.Renders.ShouldBe(renders); // OnChange would have re-rendered every subscriber
await badge.InvokeAsync(() => Services.GetRequiredService<IStore>().Dispatch(new LoadCount()));
badge.WaitForAssertion(() => badge.Markup.ShouldBe("busy")); // IsLoading changed: re-rendered
badge.Instance.Renders.ShouldBe(renders + 1); // once, for IsLoading: the Increment above added no render
}A restored slice is not loaded again
A component that loads in OnInitializedAsync loads twice on a prerendered page unless it checks what was restored. With Prerender<T> and the load rule, a slice the seed restored reads as restored, and its load effect returns early:
[Fact]
public async Task RestoredSlice_IsNotLoadedAgain()
{
var api = new FakeCounterApi();
await using var store = TestStore.Create(
ducky => ducky.AddSlice<CounterStore>().AddEffect<LoadCountOnStart>().AddEffect<LoadCountEffect>(),
services => services.AddSingleton<ICounterApi>(api));
store.Seed(new CounterState(Count: 12, IsLoading: false, Error: null)); // as the prerender seed restores it
await store.Settled();
api.Calls.ShouldBe(0);
store.State.Get<CounterState>().Count.ShouldBe(12);
}