A Store keeps an immutable RootState, (any array, tuple or object), which can be replaced by a new state. Monitoring for state replacement can indentify changes in state to drive an app. Make a new Store by calling createStore with an initialState.

Flagging all state references as Immutable guides IDEs to treat these as Immutable Objects to avoid programming errors.

Watching State

Assigning a new RootState using @watchable/store!Store.write notifies Watchers previously subscribed using @watchable/store!Watchable.watch. This mechanism ensures that app logic and renderers can track the latest state.

Immutable State: Motivation

Never modifying the state tree means when the state or a selected branch of the state is the same item as before, it is guaranteed to contain all the same values as before. This guarantee is crucial.

Immutability allows Watchers you write, renderers like React and memoizers like Reselect or React's useMemo() to use 'shallow equality checking'. There can only have been changes to an item's descendants (that might trigger a re-render or recompute) if Object.is(prevItem,nextItem)===false.

Immutability eliminates bugs and race conditions in state-change event handlers. Handlers notified of a change effectively have a snapshot of state. You don't have to handle cases where other code changed the state again before your handler read the data.

Finally, Immutability establishes a basis for advanced debugging techniques such as time-travel debugging since every state change notification includes a momentary snapshot of the app state which can be stored indefinitely.

interface Store<State> {
    read: (() => State);
    watch: ((watcher) => Unwatch);
    write: ((state) => State);
}

Type Parameters

Hierarchy (view full)

Properties

Properties

read: (() => State)

Retrieve the current state.

Type declaration

watch: ((watcher) => Unwatch)

Subscribes watcher to receive notifications.

Type declaration

Returns

  • a callback for unsubscribing
write: ((state) => State)

Store a new state.

Type declaration