Skip to content

Core concepts

Stores & state

A store is a partial class that owns a slice of state. The generator turns its fields into reactive properties and gives it a JSON identity.

The [BlexStore] attribute

Mark a partial class with [BlexStore] and the generator makes it derive from BlexStoreBase, emits the reactive members and implements the snapshot methods.

[BlexStore(Name = "counter", Persist = true)]
public partial class CounterStore
{
    // ...
}

[BlexStore] properties

Property Description
Name Display name and slice key. Defaults to the class name. Used in the state tree, DevTools, qualified action names and persistence keys.
Persist When true, the store is rehydrated on startup and saved after every action - provided a persistence provider is registered. Single fields opt out with [BlexState(Persist = false)]. See Persistence.
Version With Persist = true, the version of this store's saved state, used for it instead of options.Version: state saved under another version goes to Migrate, or is dropped. Default 0 - follow options.Version. See A store's own version.
EnforceActions When true, state changes only through the store's own actions: the generated setters are private (an outside assignment does not compile), and an assignment the store's own code makes outside an action throws once it is registered. See Actions.
RollbackOnError When true, every synchronous action is a transaction: if it throws, the store's fields go back to what they held when it started, and nothing is notified, recorded, persisted or added to the undo history. See When an action throws.
Name is the slice key

Name is what identifies the store in the global state tree, in DevTools, in action labels (counter/Increment) and in persistence keys. Changing it changes the persistence key, which strands previously saved data - bump options.Version and migrate if you rename a persisted store. A scoped instance appends its key: counter:left.

Shape requirements

The generator writes a flat, top-level partial declaration, so the class must be one it can extend:

  • declared partial - otherwise BLEX001;
  • a plain class, not a record - BLEX015. Records get value equality and a synthesized clone that fight a mutable reactive container;
  • top-level, non-generic and non-static - BLEX006;
  • with no other base class, since the generated partial adds : Bit.Blex.BlexStoreBase - BLEX016.

Constructors, interfaces, ordinary members and dependency injection all work normally. A store is just a service, so it can take an HttpClient or a repository in its constructor.

A store with dependencies
[BlexStore(Name = "weather")]
public partial class WeatherStore
{
    private readonly HttpClient _http;

    // Constructor injection works exactly as it does for any other scoped service.
    public WeatherStore(HttpClient http) => _http = http;

    [BlexState] private Forecast[]? _forecasts;

    [BlexEffect]
    private async Task OnLoad(CancellationToken ct)
        => Forecasts = await _http.GetFromJsonAsync<Forecast[]>("forecasts.json", ct);
}

[BlexState] fields

Each [BlexState] field becomes a public property whose setter runs through the dispatch pipeline: it compares, assigns, invalidates computed values, notifies subscribers and records the change for time-travel.

[BlexState] private int _count;                       // -> public int Count
[BlexState] private string _name = "";                // -> public string Name
[BlexState] private IReadOnlyList<Todo> _todos = [];   // -> public IReadOnlyList<Todo> Todos
[BlexState] private Filter _filter = Filter.All;       // -> public Filter Filter (enum, stored as a string)

The property name is derived by trimming a leading underscore and capitalizing:

FieldProperty
_countCount
countCount
_isLoggedInIsLoggedIn
Counterror BLEX012 - the field and property would collide

A [BlexState] field must be a writable instance field: static, const and readonly are rejected with BLEX008.

In a store marked Persist = true, [BlexState(Persist = false)] keeps one field out of storage - a search box's text, a selection, a cached response - while it stays part of the snapshot that DevTools, undo/redo and the prerender handoff see. See Persistence.

A setter skips an assignment of an equal value - by EqualityComparer<T>.Default, which for an array or a list means the same instance. [BlexState(Comparer = nameof(Unchanged))] names a field or property of the store holding the IEqualityComparer<T> to decide with instead, so an endpoint polled every few seconds that answers with an equal copy re-renders nothing, records nothing and writes nothing (BLEX029 when the member is missing or holds something else):

private static readonly IEqualityComparer<Message[]> Unchanged = BlexComparers.Sequence<Message>();

[BlexState(Comparer = nameof(Unchanged))] private Message[] _messages = [];

By default the properties have public setters, and an outside assignment becomes a Set X action. [BlexStore(EnforceActions = true)] makes the setters private instead, so state can only change through the store's own actions - see Actions.

Change detection

Setters compare with EqualityComparer<T>.Default. For value types and records that is structural equality, which is what you want. For a List<T>, an array or any class that does not override equality, it is reference equality - so mutating a collection in place changes nothing as far as Blex is concerned.

Live: In-place mutation vs. assignment

Both buttons add an item. Only one of them notifies anybody - watch the rendered count and the Inspector's action feed.

Rendered count 1
Actual list length 1
Items alpha

After clicking the red button the two numbers disagree: the list really did grow, but no notification fired, so the UI still shows the stale computed value. Click the blue one and both catch up.

Treat state as immutable

Always assign a new instance: Items = [.. Items, newItem]. Besides making change detection work, immutable slices are what let time-travel, undo/redo and persistence snapshot state safely. For collections that change often, use the entity adapter, which is immutable by construction.

Let Blex catch it while you develop

options.DetectInPlaceMutations = true reports, through OnError (source "mutation"), every action that changed its store's state without assigning a property - exactly what the red button above does. It serializes the store before and after each action, so turn it on in development only. It catches an action that assigned nothing at all; one that assigned a property and also mutated another in place is announced anyway, through the property it did assign.

Program.cs
builder.Services.AddBitBlexServices(options =>
{
    // Development only: every action serializes its store before and after.
    options.DetectInPlaceMutations = builder.HostEnvironment.IsDevelopment();
    options.OnError = error => logger.LogWarning(error.Exception, "[blex:{Source}] {Detail}", error.Source, error.Detail);
});

// OnError("mutation", "equalityDemo/MutateInPlace"):
//   The action 'equalityDemo/MutateInPlace' changed the store's state without assigning any
//   [BlexState] property ... Assign a new value instead: Items = [.. Items, item].
Live: In-place mutations, reported

Turn detection on and press the red button above again. The action still changes nothing anyone can see - but this time OnError hears about it, with the fix in the message, and so does the Inspector's Errors tab.

Nothing reported yet.

The switch sets the property on this app's manager while this page is open, and puts it back when you leave - so the rest of the site keeps the default, off.

Serialization

Every store gets generated SerializeState() and DeserializeState() methods keyed by the property names. This is the identity used for DevTools, undo/redo and persistence. Values round-trip through System.Text.Json with BlexJson.Options (web defaults, case-insensitive, enums as strings).

Live: Live snapshot

SerializeState() on the counter store, re-read on every change. Keep a copy, change the counter, then put the copy back with RestoreState: the counter jumps back at once, yet the Inspector's feed gains no entry - a restore is not an action.

{
  "Count": 0,
  "Step": 1
}

RestoreState is the public way to put a snapshot back by hand: it applies the values, invalidates the computed ones and raises StateChanged once, then StoreRestored and StateRestored on the manager - so cross-store selectors, undo/redo and persistence (which writes the restored state back) all follow. It records no action. DeserializeState is the raw half underneath: field writes and nothing else.

Present-but-null vs. missing

On restore, a property that is present but JSON-null resets the field to default; a missing property leaves the current value untouched. That is what lets you add a new [BlexState] field without invalidating payloads saved by an older build.

BlexStoreBase API

Your store inherits these. The public members are meant for callers; the protected ones are what the generated code calls, and are available if you hand-write a store.

Public

Member Description
string Name The store's slice key.
bool Persist Whether the store opts in to durable persistence.
int PersistVersion The store's own version of its saved state, 0 when it follows options.Version. Generated for [BlexStore(Version = n)].
event Action? StateChanged Raised after state changes so views can re-render. Fires once per action, not once per field.
event PropertyChangedEventHandler? PropertyChanged INotifyPropertyChanged, raised right after StateChanged with an empty property name - "everything may have changed" - so a XAML binding refreshes computed and effect-lifecycle properties too. What .NET MAUI binds to.
JsonObject SerializeState() Captures the current state as JSON. Generated.
void DeserializeState(JsonObject) Raw field writes from a snapshot, without notification. Generated. Prefer RestoreState.
void RestoreState(JsonObject) The safe public way to hydrate a store by hand: applies the snapshot, invalidates computed values and raises StateChanged exactly once, without recording an action.
void Batch(string, Action) Groups ad-hoc mutations into one named action - one notification, one history entry, one middleware pass. The equivalent of Pinia's $patch.
void ResetState() Restores the state the store had when it was first registered, recorded as a normal, vetoable ResetState action. No-op if the store was never registered.
string? InstanceKey The key of a scoped instance, or null for the usual single instance.
IReadOnlyList<BlexActionDescriptor> ActionDescriptors Every action of the store as data: its actions and effects, a Set X per assignable property, and ResetState. What dispatch by name uses.
BlexActionDescriptor? FindAction(string) The descriptor of the action dispatched under that name, or null.
void Dispose() Cancels in-flight effects and pending debounce waits. The DI container calls it when the scope ends. The store stays usable - disposal is a quiesce, not a kill - and a second call does nothing.

Protected

Member Description
bool IsRestoring True while the manager is applying a time-travel or restore snapshot. Use it to skip side-effects that should not run during a rewind.
bool IsObserved Whether anything (middleware, DevTools, subscribers, ActionFailed handlers) is watching. Generated wrappers use it to skip argument capture when nobody is listening.
TimeProvider TimeProvider The manager's clock (BlexManager.TimeProvider), or the system clock while unregistered. Debounced effects wait on it; read it in an action for timestamps a test can control.
string WithInstanceKey(string) Appends the instance key to the declared name. The generated Name returns it; a hand-written store that should support scoping must too.
IReadOnlyList<BlexActionDescriptor> DescribeActions() Generated override listing the store's own action descriptors.
bool EnforcesActions Generated true for EnforceActions stores: the runtime half of the guarantee.
IReadOnlyCollection<string> TransientStateKeys Generated: the properties marked [BlexState(Persist = false)].
void SetState<T>(ref T, T, string?) The generated property setter. Compares, assigns, invalidates, notifies, and records a standalone Set X action when called outside a dispatch.
void SetEffectState<T>(ref T, T) Assigns a transient effect field (loading/error). Notifies, but never records a time-travel action.
void BeginEffect(ref int) / EndEffect(ref int) Reference-count an effect's in-flight runs so IsLoading stays true until the last one finishes.
Task DebounceEffectAsync(int, CancellationToken) Waits out an effect's DebounceMilliseconds on the manager's TimeProvider - at once during a replay.
Task RunEffectAttemptsAsync(attempt, token, retryCount, retryDelayMilliseconds, timeoutMilliseconds) Runs an effect body with its retries, exponential backoff and per-attempt timeout, all inside one recorded action.
void Dispatch(string, Action, BlexActionArg[]?) Runs a mutation as one named, batched, recorded action.
Task DispatchAsync(string, Func<Task>, BlexActionArg[]?) The async variant: state changes render as they happen, but the whole operation records as one action.
bool BeginAction(string, BlexActionArg[]?) / Task DispatchApprovedAsync(...) The two halves of DispatchAsync: the veto decision first, then the body. An effect wrapper asks before it touches anything observable, so a vetoed invocation leaves no trace.
void InvalidateComputed() Generated override that marks every memoized computed value stale - after a restore, a reset, a rollback or an effect's loading flags.
void InvalidateComputed(string?) Generated override that marks stale only the computed values that read the named property, as found in their bodies. What a setter calls; an unknown name falls back to InvalidateComputed().
object?[]? CaptureRollbackState() / ApplyRollbackState(object?[]) Generated for RollbackOnError stores: the shallow copy of the state fields a synchronous action starts from, and putting it back when the action throws.
void NotifyRestored() Invalidates computed values and raises StateChanged - for hand-written stores that restore state out of band.
void CancelEffects() Generated override cancelling every in-flight effect and pending debounce. What Dispose calls.
bool IsDisposed / void Dispose(bool) Whether Dispose has run, and the hook to release resources of your own - call the base, which cancels the effects.

The IBlexStore interface

Everything the manager needs from a store. Implement it directly only if you want a store outside the generator's conventions - you then also give up batching and action recording unless you call the BlexStoreBase helpers yourself.

public interface IBlexStore
{
    string Name { get; }
    bool Persist { get; }
    event Action? StateChanged;
    JsonObject SerializeState();
    void DeserializeState(JsonObject state);
}

Lifetime

AddBitBlexStore<T> registers the store as scoped. In Blazor WebAssembly there is one scope for the whole app, so a store is effectively a singleton. In Blazor Server each circuit gets its own scope, so every user has an independent copy of the state - which is what you want. The same applies to BlexManager, BlexStatePersistor and BlexHistory.

That is one instance per DI scope. When a part of the page needs its own instance - the form in each of two open dialogs, one editor per tab - see Scoped stores.

Threads and the dispatcher

Stores are not synchronized, and neither is the dispatch pipeline: a Blazor Server circuit and a BlazorWebView keep them consistent by running every event handler, lifecycle method and render on one dispatcher. Code that is not already there - a System.Threading.Timer callback, a SignalR HubConnection.On handler, a Task.Run body, a continuation after ConfigureAwait(false) - races all of them when it changes a store.

<BlexProvider> binds the renderer's dispatcher to BlexManager.Dispatcher, and manager.InvokeAsync(...) gets there from a service that has no component to call InvokeAsync on. A store changed outside the dispatcher anyway is reported through OnError (source "dispatcher", the store's name as the detail) - the change still applies, but the report points at a race that would otherwise surface only as rare corruption in production. Turn it off with options.ReportOffDispatcherChanges = false.

public sealed class OrderFeed(HubConnection hub, BlexManager manager, OrdersStore orders)
{
    public void Start()
        => hub.On<Order>("orderPlaced", order =>
               manager.InvokeAsync(() => orders.Add(order)));   // not orders.Add(order) directly
}

Blazor WebAssembly is single-threaded, so its dispatcher never reports anything. Outside Blazor no dispatcher is bound unless you assign an IBlexDispatcher yourself.

An unhandled error has occurred. Reload 🗙