API: Middleware
SoulState supports a powerful middleware pattern that allows you to extend the store's behavior. Middleware in SoulState are higher-order functions that wrap the store creator.
devtools
Connects your SoulState store to the Redux DevTools Extension. This allows you to inspect state changes, perform time-travel debugging, and view propagation history.
Usage
import { createStore, middleware } from 'soulstate';
const { devtools } = middleware;
const store = createStore(
devtools({ name: 'CounterStore' })((set) => ({
count: 0,
inc: () => set(s => ({ count: s.count + 1 }))
}))
);
persist
Automatically persists and rehydrates your store state using localStorage or any custom storage engine.
Usage
import { createStore, middleware } from 'soulstate';
const { persist } = middleware;
const store = createStore(
persist({
key: 'app-settings',
storage: localStorage // Defaults to localStorage if window is defined
})((set) => ({
theme: 'dark',
setTheme: (theme) => set({ theme })
}))
);
Options
key: (Required) Unique key for the storage entry.storage: (Optional) Storage engine (must implementgetItemandsetItem). Defaults tolocalStorage.serialize: (Optional) Function to convert state to string.deserialize: (Optional) Function to convert string back to state.
Middleware Lifecycle
Middleware are applied during the createStore phase. They intercept the set function, allowing them to:
- Log state transitions (DevTools).
- Persist state to external storage (Persist).
- Transform state updates before they reach the core runtime.
Note on Batching
SoulState's middleware system respects the core runtime's microtask batching. Middleware like persist will only be triggered after the internal state has been updated, ensuring that only settled state is persisted.