zustand
A small, fast and scalable bearbones state-management solution using simplified flux principles. Has a comfy api based on hooks, isn't boilerplatey or opinionated.
Don't disregard it because it's cute. It has quite the claws, lots of time was spent to deal with common pitfalls, like the dreaded zombie child problem, react concurrency, and context loss between mixed renderers. It may be the one state-manager in the React space that gets all of these right.
You can try a live demo here.
First create a store
Your store is a hook! You can put anything in it: primitives, objects, functions. The set
function merges state.
Then bind your components, and that's it!
Use the hook anywhere, no providers needed. Select your state and the component will re-render on changes.
Why zustand over redux?
- Simple and un-opinionated
- Makes hooks the primary means of consuming state
- Doesn't wrap your app in context providers
- Can inform components transiently (without causing render)
Why zustand over context?
- Less boilerplate
- Renders components only on changes
- Centralized, action-based state management
Recipes
Fetching everything
You can, but bear in mind that it will cause the component to update on every state change!
Selecting multiple state slices
It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.
If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can tell zustand that you want the object to be diffed shallowly by passing the shallow
equality function.
For more control over re-rendering, you may provide any custom equality function.
Memoizing selectors
It is generally recommended to memoize selectors with useCallback. This will prevent unnecessary computations each render. It also allows React to optimize performance in concurrent mode.
If a selector doesn't depend on scope, you can define it outside the render function to obtain a fixed reference without useCallback.
Overwriting state
The set
function has a second argument, false
by default. Instead of merging, it will replace the state model. Be careful not to wipe out parts you rely on, like actions.
Async actions
Just call set
when you're ready, zustand doesn't care if your actions are async or not.
Read from state in actions
set
allows fn-updates set(state => result)
, but you still have access to state outside of it through get
.
Reading/writing state and reacting to changes outside of components
Sometimes you need to access state in a non-reactive way, or act upon the store. For these cases the resulting hook has utility functions attached to its prototype.
Using zustand without React
Zustands core can be imported and used without the React dependency. The only difference is that the create function does not return a hook, but the api utilities.
You can even consume an existing vanilla store with React:
:warning: Note that middlewares that modify set
or get
are not applied to getState
and setState
.
Transient updates (for often occuring state-changes)
The subscribe function allows components to bind to a state-portion without forcing re-render on changes. Best combine it with useEffect for automatic unsubscribe on unmount. This can make a drastic performance impact when you are allowed to mutate the view directly.
Sick of reducers and changing nested state? Use Immer!
Reducing nested structures is tiresome. Have you tried immer?
Middleware
You can functionally compose your store any way you like.
How to pipe middlewares
For a TS example see the following discussion
How to type immer middleware in TypeScript
Persist middleware
You can persist your store's data using any kind of storage.
How to use custom storage engines
You can use other storage methods outside of localStorage
and sessionStorage
by defining your own StateStorage
. A custom StateStorage
object also allows you to write middlware for the persisted store when getting or setting store data.
Can't live without redux-like reducers and action types?
Or, just use our redux-middleware. It wires up your main-reducer, sets initial state, and adds a dispatch function to the state itself and the vanilla api. Try this example.
Calling actions outside a React event handler
Because React handles setState
synchronously if it's called outside an event handler. Updating the state outside an event handler will force react to update the components synchronously, therefore adding the risk of encountering the zombie-child effect.
In order to fix this, the action needs to be wrapped in unstable_batchedUpdates
More details: https://github.com/pmndrs/zustand/issues/302
Redux devtools
devtools takes the store function as its first argument, optionally you can name the store or configure serialize options with a second argument.
Name store: devtools(store, {name: "MyStore"})
, which will be prefixed to your actions.
Serialize options: devtools(store, { serialize: { options: true } })
.
devtools will only log actions from each separated store unlike in a typical combined reducers redux store. See an approach to combining stores https://github.com/pmndrs/zustand/issues/163
React context
The store created with create
doesn't require context providers. In some cases, you may want to use contexts for dependency injection or if you want to initialize your store with props from a component. Because the store is a hook, passing it as a normal context value may violate rules of hooks. To avoid misusage, a special createContext
is provided.
createContext usage in real components
createContext usage with initialization from props (in TypeScript)
Typing your store and combine
middleware
Or, use combine
and let tsc infer types. This merges two states shallowly.
Best practices
-
You may wonder how to organize your code for better maintenance: Splitting the store into seperate slices.
-
Recommended usage for this unopinionated library: Flux inspired practice.
Testing
For information regarding testing with Zustand, visit the dedicated Wiki page.
3rd-Party Libraries
Some users may want to extends Zustand's feature set which can be done using 3rd-party libraries made by the community. For information regarding 3rd-party libraries with Zustand, visit the dedicated Wiki page.