# 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](https://www.nuget.org/packages/TimeWarp.State/12.0.0-beta.1)); from [12.0.0-beta.9](https://github.com/TimeWarpEngineering/timewarp-state/blob/v12.0.0-beta.9/documentation/release-notes/release12.0.0-beta.9.md) they target `net11.0` only, and [12.0.0-beta.11](https://github.com/TimeWarpEngineering/timewarp-state/blob/v12.0.0-beta.11/documentation/release-notes/release12.0.0-beta.11.md) 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](../compare.md) 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](https://github.com/TimeWarpEngineering/timewarp-state/tree/11.0.3/Samples/00-StateActionHandler). `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](#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](#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](#the-async-handler-becomes-an-effect)).
5. Replace `TimeWarpStateComponent` and `GetState<T>()` with `DuckyComponent<TState>` or `Select` (see [Components](#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](#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](../diagnostics/DUCKY006.md) lists the types it lacks.
9. Run the app's tests, then read [Behaviour changes](#behaviour-changes).

## Before and after

### State

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/Before/CounterState.cs#L6-L26

```csharp
// 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;
    }
}
```

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After/CounterState.cs#L6-L12

```csharp
// 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

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/Before/CounterState.cs#L30-L60

```csharp
// 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:

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After/CounterState.cs#L16-L26

```csharp
// 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);
```

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After/CounterState.cs#L30-L45

```csharp
// 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](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State.SourceGenerator/ActionSetMethodGenerator.cs#L84-L93). `[DuckyAction]` gives the same shape on anything that dispatches: `Store.IncrementCount(1)` and `await Store.IncrementCountAsync(1)` (see [Getting started](../guides/core/getting-started.md#declare-state-actions-and-a-slice)).

### The async handler becomes an effect

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/Before/CounterState.cs#L64-L99

```csharp
// 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;
            }
        }
    }
}
```

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After/CounterState.cs#L49-L65

```csharp
// 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](../guides/core/effects.md)).

### Components

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/Before/CounterView.cs#L8-L23

```csharp
// 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));
}
```

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After/CounterView.cs#L9-L19

```csharp
// 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](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State/Components/TimeWarpStateComponent.cs#L76-L80) 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](../guides/core/selectors.md)).

The component still loads in `OnInitializedAsync`, as before. On a prerendered page that runs twice; the [load rule](../guides/blazor/render-modes.md#one-load-rule-in-every-mode) moves the first load into an effect on `StoreInitialized` and, with `Prerender<T>`, runs it once per page.

### Registration

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/Before/Registration.cs#L11-L13

```csharp
// TimeWarp.State: scans the assemblies for states and registers MediatR with them.
services.AddSingleton(api);
services.AddTimeWarpState(options => options.Assemblies = [typeof(Registration).Assembly]);
```

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After/Registration.cs#L13-L18

```csharp
// 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](../guides/core/getting-started.md#register)). 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`:

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After.Tests/CounterTests.cs#L13-L30

```csharp
[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](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State/Extensions/ServiceCollectionExtensions.AddTimeWarpState.cs#L105-L119)) | `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](../guides/blazor/devtools.md)) |
| TimeWarp.State.Plus `[PersistentState(PersistentStateMethod.LocalStorage / SessionStorage)]` + manual post-processor registration | `d.Persist<TSlice>(...)` or `[Persist(Storage = PersistStorage.Session)]` ([Persistence](../guides/blazor/persistence.md)) |
| `PersistentStateMethod.PreRender`, `.Server` ([not implemented](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State.Plus/Features/Persistentence/Services/PersistenceService.cs#L35-L36) in 11.0.3) | `d.Prerender<TSlice>()` ([Prerender](../guides/blazor/prerender.md)); `PersistStorage.Server` keeps a slice in `IDistributedCache` |
| no multi-tab sync | `Persist<TSlice>(o => o.SyncAcrossTabs = true)` ([Cross-tab sync](../guides/blazor/cross-tab.md)) |
| `RouteState` (`UseRouting`) | no router state: use `NavigationManager` |
| integration tests that build a host and `Send` through `ISender` | `SliceTest`, `EffectTest`, `TestStore` in `Ducky.Testing` ([Testing](../guides/core/testing.md)) |

## 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`](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State/Extensions/TimeWarpStateOptions.cs#L20)), [clones the state](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State/Features/CloneState/Pipeline/StateTransactionBehavior.cs#L58-L60) 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.

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After.Tests/BehaviourChangeTests.cs#L32-L45

```csharp
[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](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State/Features/RenderSubscriptions/RenderSubscriptionsPostProcessor.cs#L22-L31) (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).

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After.Tests/BehaviourChangeTests.cs#L49-L68

```csharp
[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()`](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State/State/State.cs#L69-L75) 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.

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After.Tests/BehaviourChangeTests.cs#L72-L89

```csharp
[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](https://github.com/TimeWarpEngineering/timewarp-state/blob/11.0.3/Source/TimeWarp.State/Features/CloneState/Pipeline/StateTransactionBehavior.cs#L110-L120): 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`.

Source: https://github.com/phmatray/Ducky/blob/v2/docs/migration/samples/timewarp-state/After.Tests/BehaviourChangeTests.cs#L93-L110

```csharp
[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");
}
```
