Ducky Docs
Migrate pages

Migrating from TimeWarp.State

This guide takes a Blazor app from TimeWarp.State 11.0.3 (formerly Blazor-State), its latest stable release as of 2026-11-08, to Ducky 2.0. TimeWarp.State routes each action through MediatR to one async handler that mutates a mutable state. Ducky splits that handler in two: a pure reducer that returns the next immutable state, and an effect for the part that awaits.

The 12.0 line of TimeWarp.State is a pre-release: 12.0.0-beta.17 on nuget.org as of 2026-11-08. Its betas depend on TimeWarp.Mediator instead of MediatR (from 12.0.0-beta.1); from 12.0.0-beta.9 they target net11.0 only, and 12.0.0-beta.11 generates the state clones and removes the Redux DevTools integration. This guide maps the stable 11.0.3 line, which targets net8.0.

Ducky 2.0 targets net11.0 only, and it is a pre-release. How Ducky compares sets the two side by side.

Every snippet on this page comes from the compiled sample in docs/migration/samples/timewarp-state. Before is user code against TimeWarp.State 11.0.3 from nuget.org, written from TimeWarp.State's own sample. After is the same app on Ducky 2.0, and After.Tests holds its tests and one test per behaviour change below.

Checklist

  1. Target net11.0. Replace TimeWarp.State (and TimeWarp.State.Plus) with Ducky and Ducky.Blazor, and add Ducky.Testing to test projects. Remove MediatR, AnyClone and Blazored storage if nothing else uses them.
  2. Turn each State<T> into an immutable record and move Initialize() into a slice's Initial (see State).
  3. Lift each nested *ActionSet.Action to a top-level record. Mark it [DuckyAction] to keep a generated dispatch method (see Actions and handlers).
  4. Rewrite each handler's mutations as On<TAction> reducers returning state with { ... }. Split an async handler into a reducer for what it set before the await and an Effect<TAction> that dispatches what it learned (see The async handler becomes an effect).
  5. Replace TimeWarpStateComponent and GetState<T>() with DuckyComponent<TState> or Select (see Components).
  6. In _Imports.razor and the .razor files, replace @using TimeWarp.State with @using Ducky and @using Ducky.Blazor, @inherits TimeWarpStateComponent with @inherits DuckyComponent<TState> (or DuckyComponent and a Select in OnInitialized), and calls of the generated CounterState.X(...) methods with Store.X(...) or await Store.XAsync(...).
  7. Replace AddTimeWarpState with AddDucky and the generated AddDuckyGenerated_{Assembly}() (see Registration).
  8. Add a JsonSerializerContext listing the state and action types and pass it with UseJson: DevTools payloads, persisted slices and prerender seeds are serialized through it, and DUCKY006 lists the types it lacks.
  9. Run the app's tests, then read Behaviour changes.

Before and after

State

CounterState.csfrom a tested file
// TimeWarp.State: a mutable State<T> with private setters; Initialize() sets the initial values.
public interface ICounterApi
{
    Task<int> GetCountAsync(CancellationToken cancellationToken);
}

public sealed partial class CounterState : State<CounterState>
{
    public int Count { get; private set; }

    public bool IsLoading { get; private set; }

    public string? Error { get; private set; }

    public override void Initialize()
    {
        Count = 0;
        IsLoading = false;
        Error = null;
    }
}
CounterState.csfrom a tested file
// Ducky 2.0: an immutable record replaces the mutable State<T>; the slice's Initial replaces Initialize().
public interface ICounterApi
{
    Task<int> GetCountAsync(CancellationToken cancellationToken);
}

public sealed record CounterState(int Count, bool IsLoading, string? Error);

Actions and handlers

CounterState.csfrom a tested file
// TimeWarp.State: an action set nests the action and its handler in the state; the handler mutates the state in place.
public sealed partial class CounterState
{
    public static class IncrementCountActionSet
    {
        public sealed class Action : IAction
        {
            public Action(int amount)
            {
                Amount = amount;
            }

            public int Amount { get; }
        }

        public sealed class Handler : ActionHandler<Action>
        {
            public Handler(IStore store) : base(store)
            {
            }

            private CounterState CounterState => Store.GetState<CounterState>();

            public override Task Handle(Action action, CancellationToken cancellationToken)
            {
                CounterState.Count += action.Amount;
                return Task.CompletedTask;
            }
        }
    }
}

The action leaves its state class, and the handler's mutation becomes a reducer in the slice:

CounterState.csfrom a tested file
// Ducky 2.0: the actions are top-level records. [DuckyAction] generates Store.IncrementCount(1) and
// await Store.IncrementCountAsync(1), the counterparts of TimeWarp.State's generated CounterState.IncrementCount(...).
[DuckyAction]
public sealed record IncrementCount(int Amount);

[DuckyAction]
public sealed record LoadCount;

public sealed record CountLoaded(int Count);

public sealed record CountLoadFailed(string Error);
CounterState.csfrom a tested file
// Ducky 2.0: each mutation of a handler becomes a pure reducer that returns the next state. The async handler splits in
// two: LoadCount's reducer sets IsLoading at once, and the effect below reports the result as CountLoaded or CountLoadFailed.
public sealed class CounterSlice : Slice<CounterState>
{
    public CounterSlice()
    {
        On<IncrementCount>((state, action) => state with { Count = state.Count + action.Amount });
        On<LoadCount>(state => state with { IsLoading = true, Error = null });
        On<CountLoaded>((state, action) => state with { Count = action.Count, IsLoading = false });
        On<CountLoadFailed>((state, action) => state with { IsLoading = false, Error = action.Error });
    }

    public override string Key => "counter";

    protected override CounterState Initial => new(Count: 0, IsLoading: false, Error: null);
}

TimeWarp.State's generator turns each *ActionSet into a method on the state, await CounterState.IncrementCount(amount: 1), which sends the action through MediatR. [DuckyAction] gives the same shape on anything that dispatches: Store.IncrementCount(1) and await Store.IncrementCountAsync(1) (see Getting started).

The async handler becomes an effect

CounterState.csfrom a tested file
// TimeWarp.State: one async handler both awaits the API and mutates the state, before and after the await.
public sealed partial class CounterState
{
    public static class LoadCountActionSet
    {
        public sealed class Action : IAction;

        public sealed class Handler : ActionHandler<Action>
        {
            private readonly ICounterApi _api;

            public Handler(IStore store, ICounterApi api) : base(store)
            {
                _api = api;
            }

            private CounterState CounterState => Store.GetState<CounterState>();

            public override async Task Handle(Action action, CancellationToken cancellationToken)
            {
                CounterState.IsLoading = true;
                CounterState.Error = null;
                try
                {
                    CounterState.Count = await _api.GetCountAsync(cancellationToken);
                }
                catch (HttpRequestException exception)
                {
                    CounterState.Error = exception.Message;
                }

                CounterState.IsLoading = false;
            }
        }
    }
}
CounterState.csfrom a tested file
// Ducky 2.0: the awaiting half of the handler, with the run's token. Switch: a newer LoadCount cancels the running one.
public sealed class LoadCountEffect(ICounterApi api) : Effect<LoadCount>
{
    public override Concurrency Policy => Concurrency.Switch;

    public override async Task Handle(LoadCount action, EffectContext context, CancellationToken cancellationToken)
    {
        try
        {
            context.Dispatch(new CountLoaded(await api.GetCountAsync(cancellationToken)));
        }
        catch (HttpRequestException exception)
        {
            context.Dispatch(new CountLoadFailed(exception.Message));
        }
    }
}

What the handler set before its await is now LoadCount's reducer, above; what it set after is CountLoaded or CountLoadFailed, dispatched by the effect. The effect takes its services through its constructor, as the handler did, and its token is cancelled when the run is superseded or the store is disposed, which replaces State<T>.CancelOperations(). Policy picks Merge (the default), Switch, Exhaust or Queue (see Effects and concurrency policies).

Components

CounterView.csfrom a tested file
// TimeWarp.State: GetState<T>() subscribes the component to the whole state; the generated methods send the actions.
public sealed class CounterView : TimeWarpStateComponent
{
    private CounterState CounterState => GetState<CounterState>();

    public Task IncrementAsync() => CounterState.IncrementCount(amount: 1); // generated from IncrementCountActionSet

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        await CounterState.LoadCount(); // generated from LoadCountActionSet
    }

    protected override void BuildRenderTree(RenderTreeBuilder builder) =>
        builder.AddContent(0, CounterState.IsLoading ? "loading" : CounterState.Count.ToString(CultureInfo.InvariantCulture));
}
CounterView.csfrom a tested file
// Ducky 2.0: DuckyComponent<TState>'s State is a selection of the whole slice; the generated helpers dispatch.
public sealed class CounterView : DuckyComponent<CounterState>
{
    public Task<DispatchResult> IncrementAsync() => Store.IncrementCountAsync(1); // completes once reduced

    protected override async Task OnInitializedAsync() =>
        await Store.LoadCountAsync(); // completes once LoadCount is reduced, not once the count arrived

    protected override void BuildRenderTree(RenderTreeBuilder builder) =>
        builder.AddContent(0, State.IsLoading ? "loading" : State.Count.ToString(CultureInfo.InvariantCulture));
}

GetState<T>() subscribes the component to every change of that state. DuckyComponent<TState> does the same through its State property; a DuckyComponent that calls Select((CounterState s) => s.Count) in OnInitialized re-renders only when that value changed, which covers what RegisterRenderTrigger was for (see Selectors).

The component still loads in OnInitializedAsync, as before. On a prerendered page that runs twice; the load rule moves the first load into an effect on StoreInitialized and, with Prerender<T>, runs it once per page.

Registration

Registration.csfrom a tested file
// TimeWarp.State: scans the assemblies for states and registers MediatR with them.
services.AddSingleton(api);
services.AddTimeWarpState(options => options.Assemblies = [typeof(Registration).Assembly]);
Registration.csfrom a tested file
// Ducky 2.0: the generated AddDuckyGenerated_{Assembly}() registers the slice and the effect; no MediatR, no scan.
services.AddSingleton(api);
services.AddDucky(ducky => ducky
    .AddDuckyGenerated_TimeWarpSample_After()
    .UseJson(AppJson.Default)
    .AddBlazor());

AddDuckyGenerated_{Assembly}() is generated at build time for each assembly that declares slices or effects (see Getting started). The AppJson passed to UseJson is a JsonSerializerContext listing the state and action types: Ducky serializes DevTools payloads, persisted slices and prerender seeds through it, never by reflection.

The tests use Ducky.Testing instead of a host and ISender:

CounterTests.csfrom a tested file
[Fact]
public void IncrementCount_AddsAmount() =>
    SliceTest.For<CounterSlice, CounterState>()
        .Given(new CounterState(Count: 3, IsLoading: false, Error: null))
        .When(new IncrementCount(2))
        .Then(new CounterState(Count: 5, IsLoading: false, Error: null));

[Fact]
public async Task LoadCountEffect_ApiAnswers_DispatchesCountLoaded()
{
    var api = new FakeCounterApi();
    var running = EffectTest.Run<LoadCountEffect, LoadCount>(new LoadCount(), services: s => s.AddSingleton<ICounterApi>(api));
    api.Complete(0, 42);

    var run = await running;

    run.Dispatched.ShouldBe([new CountLoaded(42)]);
}

Mapping table

TimeWarp.State column: TimeWarp.State 11.0.3, as of 2026-11-08.

TimeWarp.State 11.0.3 Ducky 2.0
TimeWarp.State (net8.0; depends on MediatR, version 12.4.1 or later, and AnyClone) Ducky, Ducky.Blazor (net11.0; no MediatR)
services.AddTimeWarpState(o => o.Assemblies = [...]) (assembly scan and MediatR registration) services.AddDucky(d => d.AddDuckyGenerated_{Assembly}()), generated at build time
sealed partial class XState : State<XState> with private set properties a record state and a Slice<TState>
Initialize() protected override TState Initial
nested XActionSet.Action : IAction (a MediatR IRequest) a top-level record, no interface
generated await XState.DoThing(args) [DuckyAction]: Store.DoThing(args) or await Store.DoThingAsync(args)
Mediator.Send(new XState.XActionSet.Action(...)) Store.Dispatch(action) or await Store.DispatchAsync(action)
ActionHandler<TAction> mutating Store.GetState<XState>() On<TAction>((state, action) => state with { ... }) in the slice
an async Handle that awaits a service a reducer for the start, plus an Effect<TAction> that dispatches the result
the CancellationToken of Handle, State<T>.CancelOperations() the effect's run token; Policy => Concurrency.Switch cancels the previous run
StateTransactionBehavior (on by default): clone before, restore and publish ExceptionNotification on a throw nothing to clone: a reducer that throws commits nothing and dispatches ReducerFailed; an effect that throws dispatches EffectFailed
TimeWarpStateComponent, GetState<T>() DuckyComponent<TState> (State), or DuckyComponent + Select in OnInitialized
RegisterRenderTrigger<TState>(...) Select(selector): the component re-renders when the selected value changes
GetPreviousState<T>() ActionContext.PreviousState in a Middleware
MediatR IPipelineBehavior<,>, IRequestPreProcessor<>, IRequestPostProcessor<,> Middleware (MayDispatch, BeforeReduce, AfterReduce) for the synchronous part, an effect for the asynchronous part
o.UseReduxDevTools() + <TimeWarpJavaScriptInterop /> + <ReduxDevTools /> d.UseDevTools(...) guarded by IsDevelopment(), no component (Redux DevTools)
TimeWarp.State.Plus [PersistentState(PersistentStateMethod.LocalStorage / SessionStorage)] + manual post-processor registration d.Persist<TSlice>(...) or [Persist(Storage = PersistStorage.Session)] (Persistence)
PersistentStateMethod.PreRender, .Server (not implemented in 11.0.3) d.Prerender<TSlice>() (Prerender); PersistStorage.Server keeps a slice in IDistributedCache
no multi-tab sync Persist<TSlice>(o => o.SyncAcrossTabs = true) (Cross-tab sync)
RouteState (UseRouting) no router state: use NavigationManager
integration tests that build a host and Send through ISender SliceTest, EffectTest, TestStore in Ducky.Testing (Testing)

Behaviour changes

Each comes with the test that pins it.

State is immutable

A TimeWarp.State handler mutates the state in place, so StateTransactionBehavior, on by default (UseStateTransactionBehavior), clones the state before every action to be able to roll it back. A Ducky reducer returns a new record and the store swaps the reference: a snapshot you hold never changes, and there is no clone to make or to get wrong.

BehaviourChangeTests.csfrom a tested file
[Fact]
public async Task Reducer_ReturnsANewState_EarlierSnapshotsNeverChange()
{
    await using var store = TestStore.Create(ducky => ducky.AddSlice<CounterSlice>());
    var snapshot = store.State; // the whole store's state, as a component or an effect reads it

    await store.IncrementCountAsync(5);

    // The store committed a new snapshot instead of changing the one held: nothing to clone, nothing to roll back.
    snapshot.Get<CounterState>().Count.ShouldBe(0);
    store.State.ShouldNotBeSameAs(snapshot);
    store.State.Version.ShouldBe(snapshot.Version + 1);
    store.State.Get<CounterState>().Count.ShouldBe(5);
}

What an async handler set before its await is rendered at once

TimeWarp.State re-renders a state's subscribers in a MediatR post-processor, after the handler returns (Blazor may re-render the calling component at the handler's first await), and the generated method completes after the whole handler. In Ducky, LoadCount is reduced and its subscribers notified before the effect's API call answers, and await Store.LoadCountAsync() completes then, not when the count arrives. To wait for the effect too, use WhenIdleAsync() (or TestStore.Settled() in a test).

BehaviourChangeTests.csfrom a tested file
[Fact]
public async Task LoadCount_IsReducedBeforeTheApiAnswers()
{
    var api = new FakeCounterApi();
    await using var store = TestStore.Create(
        ducky => ducky.AddSlice<CounterSlice>().AddEffect<LoadCountEffect>(),
        services => services.AddSingleton<ICounterApi>(api));

    var seen = new List<bool>();
    using var isLoading = store.Select(s => s.Get<CounterState>().IsLoading, seen.Add);

    var result = await store.LoadCountAsync(); // completes after the reduce, not after the effect

    result.ShouldBe(DispatchResult.Reduced);
    store.State.Get<CounterState>().IsLoading.ShouldBeTrue();
    seen.ShouldBe([true]); // the subscriber was notified while the API call is still pending
    api.Complete(0, 7);
    await store.Settled(); // wait for the effect too
    store.State.Get<CounterState>().ShouldBe(new CounterState(Count: 7, IsLoading: false, Error: null));
}

Effects have a concurrency policy

TimeWarp.State applies no concurrency policy: each Send runs its handler, even while an earlier one for the same action is still running, and CancelOperations() cancels the token that every operation of the state shares. A Ducky effect picks a policy per effect: with Switch, a newer LoadCount cancels only the running load, and the late result of the superseded run is dropped.

BehaviourChangeTests.csfrom a tested file
[Fact]
public async Task SwitchEffect_NewerLoad_CancelsAndDropsTheOlderRun()
{
    var api = new FakeCounterApi(honourCancellation: false); // an API that ignores the token and answers late
    await using var store = TestStore.Create(
        ducky => ducky.AddSlice<CounterSlice>().AddEffect<LoadCountEffect>(),
        services => services.AddSingleton<ICounterApi>(api));

    store.LoadCount();
    store.LoadCount();
    api.Token(0).IsCancellationRequested.ShouldBeTrue();

    api.Complete(1, 5);
    api.Complete(0, 99); // the superseded run answers late: its dispatch is dropped
    await store.Settled();

    store.State.Get<CounterState>().Count.ShouldBe(5);
}

Failures are actions, not swallowed exceptions

When a TimeWarp.State handler throws, StateTransactionBehavior restores the state, publishes an ExceptionNotification and returns: by default the caller sees no exception. In Ducky, a reducer that throws commits nothing in any slice, the dispatch ends Failed, and the store dispatches ReducerFailed; an effect that throws dispatches EffectFailed. Handle either with an effect on that failure action, and see them in TestStore.Failures.

BehaviourChangeTests.csfrom a tested file
[Fact]
public async Task Failures_AreActions_NeverSwallowed()
{
    await using var store = TestStore.Create(ducky => ducky
        .AddSlice<CounterSlice>()
        .AddSlice<Fixtures.FragileSlice>()
        .AddEffect<Fixtures.ExplodeEffect>());

    var result = await store.IncrementCountAsync(5); // FragileSlice throws for IncrementCount

    result.ShouldBe(DispatchResult.Failed);
    store.State.Get<CounterState>().Count.ShouldBe(0); // nothing committed, in any slice
    store.Failures.ShouldHaveSingleItem().ShouldBeOfType<ReducerFailed>().Exception.Message.ShouldBe("boom");

    store.Dispatch(new Fixtures.Explode());
    await store.Settled();
    store.Failures[^1].ShouldBeOfType<EffectFailed>().Exception.Message.ShouldBe("effect boom");
}