Hotfix section linking (#3410)
Initial plan
Fix docs section anchors
Co-authored-by: dbritto-dev 1697714+dbritto-dev@users.noreply.github.com
- docs: align toc anchors with slugify ids
Co-authored-by: dbritto-dev 1697714+dbritto-dev@users.noreply.github.com
- docs: remove angle-bracket toc links
Co-authored-by: dbritto-dev 1697714+dbritto-dev@users.noreply.github.com
- docs: strip backticks from anchor links
Co-authored-by: dbritto-dev 1697714+dbritto-dev@users.noreply.github.com
- docs: convert code headings to clean ids
Co-authored-by: dbritto-dev 1697714+dbritto-dev@users.noreply.github.com
- docs: replace html headings with markdown
Co-authored-by: dbritto-dev 1697714+dbritto-dev@users.noreply.github.com
Update shallow.md
chore: run pnpm fix
Co-authored-by: dbritto-dev 1697714+dbritto-dev@users.noreply.github.com
Co-authored-by: copilot-swe-agent[bot] 198982749+Copilot@users.noreply.github.com Co-authored-by: dbritto-dev 1697714+dbritto-dev@users.noreply.github.com Co-authored-by: Danilo Britto dbritto.dev@gmail.com
版权所有:中国计算机学会技术支持:开源发展技术委员会
京ICP备13000930号-9
京公网安备 11010802032778号
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 dealing 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 and read the docs.
First create a store
Your store is a hook! You can put anything in it: primitives, objects, functions. State has to be updated immutably and the
setfunction merges state to help it.Then bind your components, and that’s it!
Use the hook anywhere, no providers are needed. Select your state and the component will re-render on changes.
Why zustand over redux?
Why zustand over context?
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 use useShallow to prevent unnecessary rerenders when the selector output does not change according to shallow equal.
For more control over re-rendering, you may provide any custom equality function (this example requires the use of
createWithEqualityFn).Overwriting state
The
setfunction has a second argument,falseby 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
setwhen you’re ready, zustand doesn’t care if your actions are async or not.Read from state in actions
setallows fn-updatesset(state => result), but you still have access to state outside of it throughget.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 subscribe with selector
If you need to subscribe with a selector,
subscribeWithSelectormiddleware will help.With this middleware
subscribeaccepts an additional signature:Using zustand without React
Zustand 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 use a vanilla store with
useStorehook available since v4.setorgetare not applied togetStateandsetState.Transient updates (for often occurring 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 states? Use Immer!
Reducing nested structures is tiresome. Have you tried immer?
Alternatively, there are some other solutions.
Persist middleware
You can persist your store’s data using any kind of storage.
See the full documentation for this middleware.
Immer middleware
Immer is available as middleware too.
Can’t live without redux-like reducers and action types?
Or, just use our redux-middleware. It wires up your main-reducer, sets the initial state, and adds a dispatch function to the state itself and the vanilla API.
Redux devtools
Install the Redux DevTools Chrome extension to use the devtools middleware.
One redux devtools connection for multiple stores
Assigning different connection names will separate stores in redux devtools. This also helps group different stores into separate redux devtools connections.
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(..., {name: "MyStore"}), which will create a separate instance named “MyStore” in the devtools.Serialize options:
devtools(..., { serialize: { options: true } }).Logging Actions
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
You can log a specific action type for each
setfunction by passing a third parameter:You can also log the action’s type along with its payload:
If an action type is not provided, it is defaulted to “anonymous”. You can customize this default value by providing an
anonymousActionTypeparameter:If you wish to disable devtools (on production for instance). You can customize this setting by providing the
enabledparameter:React context
The store created with
createdoesn’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 normal store is a hook, passing it as a normal context value may violate the rules of hooks.The recommended method available since v4 is to use the vanilla store.
TypeScript Usage
Basic typescript usage doesn’t require anything special except for writing
create<State>()(...)instead ofcreate(...)…A more detailed TypeScript guide is here and there.
Best practices
Third-Party Libraries
Some users may want to extend Zustand’s feature set which can be done using third-party libraries made by the community. For information regarding third-party libraries with Zustand, visit the doc.
Comparison with other libraries