Ducky Docs
Other guides pages

Migrating from Bustand

Bustand's Zustand-style stores map to Ducky 2.0's SliceStore<TState>. For a store without injected services the move is a rename. A store that injects a service, or has a method that awaits I/O and then sets state, needs one extra piece: an effect.

Every snippet on this page comes from the compiled sample in docs/migration/samples/bustand. Before builds against Bustand: Bustand was never published to nuget.org, so the sample uses a verbatim copy of its source in docs/migration/samples/legacy/Bustand. After is the same app on Ducky 2.0, and After.Tests holds its tests.

Checklist

  1. Replace the Bustand packages with Ducky and Ducky.Blazor, and add Ducky.Testing to test projects.
  2. Derive each store from SliceStore<TState> and rename InitialState to Initial.
  3. Move constructor-injected services, InitializeAsync and every store method that awaits a service into effects (see The load becomes an effect).
  4. Replace UseState with Select in OnInitialized (see Components).
  5. Replace AddBustand with AddDucky (see Registration), then run the app's tests.

Before and after

The store

UserStore.csfrom a tested file
// Bustand: a ZustandStore injects its services and loads in InitializeAsync, then sets state.
public sealed record User(string Name);

public sealed record UserState(User? User, bool IsLoading = false);

public interface IUserService
{
    Task<User> GetCurrentUserAsync();
}

[BustandStore]
public sealed class UserStore : ZustandStore<UserState>
{
    private readonly IUserService _userService;

    public UserStore(IUserService userService) => _userService = userService;

    protected override UserState InitialState => new(User: null, IsLoading: true);

    public void Rename(string name) => Set(state => state with { User = new User(name) });

    public Task SignOutAsync() => SetAsync(new UserState(User: null));

    protected override async Task InitializeAsync()
    {
        var user = await _userService.GetCurrentUserAsync();
        await SetAsync(state => state with { User = user, IsLoading = false });
    }
}
UserStore.csfrom a tested file
// Ducky 2.0: a SliceStore has no constructor dependencies; Set and SetAsync take a mutator that runs at reduce time.
public sealed record User(string Name);

public sealed record UserState(User? User, bool IsLoading = false);

public interface IUserService
{
    Task<User> GetCurrentUserAsync(CancellationToken cancellationToken);
}

public sealed class UserStore : SliceStore<UserState>
{
    protected override UserState Initial => new(User: null, IsLoading: true);

    public void Rename(string name) => Set(state => state with { User = new User(name) });

    public Task<DispatchResult> SignOutAsync() => SetAsync(_ => new UserState(User: null)); // SetAsync(TState) => SetAsync(_ => value)

    // What the effect calls: awaiting the task gives read-your-writes.
    public Task<DispatchResult> SetUserAsync(User u) => SetAsync(_ => new(u));
}

Set and SetAsync keep their names and stay protected, as in Bustand. Both take a mutator: Set(Func) is unchanged, and Set(TState) and SetAsync(TState) become Set(_ => value) and SetAsync(_ => value). The mutator runs when the store reduces the change, against the latest state, so concurrent changes no longer overwrite each other (Bustand's lost updates). SetAsync returns Task<DispatchResult> and completes once the change is reduced: awaiting it gives read-your-writes. A SliceStore is still a slice, so it can also react to actions with On<T> (see SliceStore).

The load becomes an effect

A SliceStore has a parameterless constructor and never awaits. InitializeAsync, a constructor-injected service, or a store method that awaits a service and then sets state, becomes an effect. The effect injects the service and the SliceStore, awaits the work with its run token, then calls a public SliceStore method: here SetUserAsync, which wraps SetAsync. An Effect<StoreInitialized> runs once, when the store is ready; work started by a user action is an Effect<TAction> on that action, with a concurrency policy (Switch, Exhaust) Bustand's methods never had.

UserStore.csfrom a tested file
// Ducky 2.0: InitializeAsync becomes an Effect<StoreInitialized> that injects the service and the SliceStore.
public sealed class LoadUser(IUserService users, UserStore store) : Effect<StoreInitialized>
{
    public override async Task Handle(StoreInitialized action, EffectContext context, CancellationToken cancellationToken) =>
        await store.SetUserAsync(await users.GetCurrentUserAsync(cancellationToken));
}

The effect's test lets the store build it, so it injects the store's own UserStore; TestStore.GetSlice<UserStore>() reads that instance (see Testing):

UserStoreTests.csfrom a tested file
var run = await EffectTest.Run<LoadUser, StoreInitialized>(
    new StoreInitialized(),
    ducky => ducky.AddSlice<UserStore>(),
    store => users = store.GetSlice<UserStore>(),
    services: s => s.AddSingleton<IUserService>(fake));

Components

UserBadge.csfrom a tested file
// Bustand: UseState subscribes to a selected value of the injected store.
public sealed class UserBadge : ZustandComponent<UserStore, UserState>
{
    protected override void BuildRenderTree(RenderTreeBuilder builder) =>
        builder.AddContent(0, UseState(state => state.User?.Name ?? "guest").Value);
}
UserBadge.csfrom a tested file
// Ducky 2.0: Select in OnInitialized replaces UseState; the component re-renders when the selected value changes.
public sealed class UserBadge : DuckyComponent
{
    private Selection<string>? _name;

    protected override void OnInitialized() => _name = Select((UserState state) => state.User?.Name ?? "guest");

    protected override void BuildRenderTree(RenderTreeBuilder builder) => builder.AddContent(0, _name!.Value);
}

SliceStore.State is a point-in-time read, not a subscription. Markup that must follow changes (the load, a restore from storage, changes made by other components) reads through a Select in OnInitialized or <DuckySelect>; mutations keep calling the SliceStore's methods.

Registration

Registration.csfrom a tested file
// Bustand: Scrutor scans for [BustandStore] classes; the store's services come from DI.
services.AddSingleton(users);
services.AddBustand(options => options.ScanAssemblyContaining<UserStore>());
Registration.csfrom a tested file
// Ducky 2.0: the generated AddDuckyGenerated_{Assembly}() registers UserStore and LoadUser; no circuit handler.
services.AddSingleton(users);
services.AddDucky(ducky => ducky
    .AddDuckyGenerated_Bustand_After()
    .AddBlazor());

Mapping table

Bustand Ducky 2.0
ZustandStore<TState>, InitialState SliceStore<TState>, Initial
IStore<TState> inject the SliceStore itself (AddSlice<T>() registers it, resolved to the instance the store owns)
Set(Func) / Set(TState) Set(Func) unchanged / Set(_ => value)
SetAsync(Func) / SetAsync(TState) SetAsync(Func) (returns Task<DispatchResult> and completes after the reduce) / SetAsync(_ => value); both are protected, as in Bustand
constructor-injected services, an overridden InitializeAsync, or a store method that awaits a service and then sets state an Effect (an Effect<StoreInitialized> for the initial load) that injects the service and the SliceStore, awaits the work with its run token and calls a public SliceStore method wrapping Set, or returning SetAsync's task for read-your-writes, like SetUserAsync above
Subscribe(Action), Subscribe<TSlice>(selector, callback), the StateChanged event store.Select<TState, T>(selector, onChange); dispose the Selection to unsubscribe. onChange runs on the draining thread
IsInitialized State.Get<PersistenceState>().Status, or an effect on StoreInitialized
an OnStateChanged() override an onChange callback, or a Middleware with AfterReduce
IMiddleware<TState> / IAsyncMiddleware<TState> Middleware / an Effect: middleware hooks are synchronous
ZustandComponent<TStore,TState>.UseState(sel), UseStateResult<T> DuckyComponent.Select(sel) in OnInitialized (or <DuckySelect>), Selection<T>
ZustandComponentScoped<TStore,TState>, ZustandScope DuckyComponent over the app store; 2.0 has no component-scoped store
[BustandStore] + Scrutor the generated AddDuckyGenerated_{Asm}()
[Persist(StorageType)] [Persist(Storage = PersistStorage.Session)] (or Local), or Persist<T>(...) in the registration
Bustand.DevTools Redux DevTools (UseDevTools())
BustandCircuitHandler nothing: interactivity is automatic