Overview
ThecreateStore function creates a minimal, reactive store for managing global application state. It provides a simple API for getting and setting state, subscribing to changes, and cleaning up resources.
Inspired by Zustand’s approach, createStore offers a lightweight alternative to Redux with minimal boilerplate.
Signature
A function that receives
setState and getState as arguments and returns the initial state object (optionally with action methods).Function Signature:setState(partial, replace)- Function to update the stategetState()- Function to get the current state- Returns an object representing the initial state
Return Value
Returns a store object with the following methods:Returns the current state object.
Updates the state. Can accept an object or a function.Signature: Note: State updates are skipped if the next state is identical to the current state (using
setState(partial, replace)partial- Object with state updates, or a function(state) => updatesreplace- Boolean. Iftrue, replaces entire state. Iffalse(default), merges with existing state.
Object.is).Subscribes to state changes. Returns an unsubscribe function.Signature:
subscribe(listener)listener- Function called with the new state whenever it changes
Cleans up the store by removing all listeners.
Examples
Basic Counter Store
Store with Complex State
Subscribing to Changes
State Update Behavior
Merge vs Replace
By default,setState merges updates with the existing state:
replace parameter to replace the entire state:
Function Updates
Use a function when the new state depends on the current state:Best Practices
Keep Actions in the Store
Define action methods directly in the initial state object for better encapsulation and easier testing.
Use Selectors with connect
When connecting to components, use selector functions to only pass the needed state, optimizing re-renders.
Clean Up Subscriptions
Always call the unsubscribe function returned by
subscribe() to prevent memory leaks.Destroy Stores
Call
store.destroy() when a store is no longer needed to clean up all listeners.See Also
- connect - Connect a store to GlyphUI components
- createActions - Create bound action creators for a store