- Notifications
You must be signed in to change notification settings - Fork0
🐻 Bear necessities for state management in React
License
Prains/zustand
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
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 dreadedzombie child problem,react concurrency, andcontext 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 demohere.
npm i zustand
Your store is a hook! You can put anything in it: primitives, objects, functions. State has to be updated immutably and theset functionmerges state to help it.
import{create}from'zustand'constuseBearStore=create((set)=>({bears:0,increasePopulation:()=>set((state)=>({bears:state.bears+1})),removeAllBears:()=>set({bears:0}),}))
Use the hook anywhere, no providers are needed. Select your state and the component will re-render on changes.
functionBearCounter(){constbears=useBearStore((state)=>state.bears)return<h1>{bears} around here ...</h1>}functionControls(){constincreasePopulation=useBearStore((state)=>state.increasePopulation)return<buttononClick={increasePopulation}>one up</button>}
- 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)
- Less boilerplate
- Renders components only on changes
- Centralized, action-based state management
You can, but bear in mind that it will cause the component to update on every state change!
conststate=useBearStore()
It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.
constnuts=useBearStore((state)=>state.nuts)consthoney=useBearStore((state)=>state.honey)
If you want to construct a single object with multiple state-picks inside, similar to redux's mapStateToProps, you can useuseShallow to prevent unnecessary rerenders when the selector output does not change according to shallow equal.
import{create}from'zustand'import{useShallow}from'zustand/react/shallow'constuseBearStore=create((set)=>({bears:0,increasePopulation:()=>set((state)=>({bears:state.bears+1})),removeAllBears:()=>set({bears:0}),}))// Object pick, re-renders the component when either state.nuts or state.honey changeconst{ nuts, honey}=useBearStore(useShallow((state)=>({nuts:state.nuts,honey:state.honey})),)// Array pick, re-renders the component when either state.nuts or state.honey changeconst[nuts,honey]=useBearStore(useShallow((state)=>[state.nuts,state.honey]),)// Mapped picks, re-renders the component when state.treats changes in order, count or keysconsttreats=useBearStore(useShallow((state)=>Object.keys(state.treats)))
For more control over re-rendering, you may provide any custom equality function.
consttreats=useBearStore((state)=>state.treats,(oldTreats,newTreats)=>compare(oldTreats,newTreats),)
Theset 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.
importomitfrom'lodash-es/omit'constuseFishStore=create((set)=>({salmon:1,tuna:2,deleteEverything:()=>set({},true),// clears the entire store, actions includeddeleteTuna:()=>set((state)=>omit(state,['tuna']),true),}))
Just callset when you're ready, zustand doesn't care if your actions are async or not.
constuseFishStore=create((set)=>({fishies:{},fetch:async(pond)=>{constresponse=awaitfetch(pond)set({fishies:awaitresponse.json()})},}))
set allows fn-updatesset(state => result), but you still have access to state outside of it throughget.
constuseSoundStore=create((set,get)=>({sound:'grunt',action:()=>{constsound=get().sound...
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.
constuseDogStore=create(()=>({paw:true,snout:true,fur:true}))// Getting non-reactive fresh stateconstpaw=useDogStore.getState().paw// Listening to all changes, fires synchronously on every changeconstunsub1=useDogStore.subscribe(console.log)// Updating state, will trigger listenersuseDogStore.setState({paw:false})// Unsubscribe listenersunsub1()// You can of course use the hook as you always wouldfunctionComponent(){constpaw=useDogStore((state)=>state.paw)...
If you need to subscribe with a selector,subscribeWithSelector middleware will help.
With this middlewaresubscribe accepts an additional signature:
subscribe(selector,callback,options?:{equalityFn,fireImmediately}):Unsubscribe
import{subscribeWithSelector}from'zustand/middleware'constuseDogStore=create(subscribeWithSelector(()=>({paw:true,snout:true,fur:true})),)// Listening to selected changes, in this case when "paw" changesconstunsub2=useDogStore.subscribe((state)=>state.paw,console.log)// Subscribe also exposes the previous valueconstunsub3=useDogStore.subscribe((state)=>state.paw,(paw,previousPaw)=>console.log(paw,previousPaw),)// Subscribe also supports an optional equality functionconstunsub4=useDogStore.subscribe((state)=>[state.paw,state.fur],console.log,{equalityFn:shallow},)// Subscribe and fire immediatelyconstunsub5=useDogStore.subscribe((state)=>state.paw,console.log,{fireImmediately:true,})
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.
import{createStore}from'zustand/vanilla'conststore=createStore((set)=> ...)const{ getState, setState, subscribe, getInitialState}=storeexportdefaultstore
You can use a vanilla store withuseStore hook available since v4.
import{useStore}from'zustand'import{vanillaStore}from'./vanillaStore'constuseBoundStore=(selector)=>useStore(vanillaStore,selector)
set orget are not applied togetState andsetState.
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 adrastic performance impact when you are allowed to mutate the view directly.
constuseScratchStore=create((set)=>({scratches:0, ...}))constComponent=()=>{// Fetch initial stateconstscratchRef=useRef(useScratchStore.getState().scratches)// Connect to the store on mount, disconnect on unmount, catch state-changes in a referenceuseEffect(()=>useScratchStore.subscribe(state=>(scratchRef.current=state.scratches)),[])...
Reducing nested structures is tiresome. Have you triedimmer?
import{produce}from'immer'constuseLushStore=create((set)=>({lush:{forest:{contains:{a:'bear'}}},clearForest:()=>set(produce((state)=>{state.lush.forest.contains=null}),),}))constclearForest=useLushStore((state)=>state.clearForest)clearForest()
Alternatively, there are some other solutions.
You can persist your store's data using any kind of storage.
import{create}from'zustand'import{persist,createJSONStorage}from'zustand/middleware'constuseFishStore=create(persist((set,get)=>({fishes:0,addAFish:()=>set({fishes:get().fishes+1}),}),{name:'food-storage',// name of the item in the storage (must be unique)storage:createJSONStorage(()=>sessionStorage),// (optional) by default, 'localStorage' is used},),)
See the full documentation for this middleware.
Immer is available as middleware too.
import{create}from'zustand'import{immer}from'zustand/middleware/immer'constuseBeeStore=create(immer((set)=>({bees:0,addBees:(by)=>set((state)=>{state.bees+=by}),})),)
consttypes={increase:'INCREASE',decrease:'DECREASE'}constreducer=(state,{ type, by=1})=>{switch(type){casetypes.increase:return{grumpiness:state.grumpiness+by}casetypes.decrease:return{grumpiness:state.grumpiness-by}}}constuseGrumpyStore=create((set)=>({grumpiness:0,dispatch:(args)=>set((state)=>reducer(state,args)),}))constdispatch=useGrumpyStore((state)=>state.dispatch)dispatch({type:types.increase,by:2})
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.
import{redux}from'zustand/middleware'constuseGrumpyStore=create(redux(reducer,initialState))
import{devtools}from'zustand/middleware'// Usage with a plain action store, it will log actions as "setState"constusePlainStore=create(devtools((set)=> ...))// Usage with a redux store, it will log full action typesconstuseReduxStore=create(devtools(redux(reducer,initialState)))
One redux devtools connection for multiple stores
import{devtools}from'zustand/middleware'// Usage with a plain action store, it will log actions as "setState"constusePlainStore1=create(devtools((set)=> ...,{ name,store:storeName1}))constusePlainStore2=create(devtools((set)=> ...,{ name,store:storeName2}))// Usage with a redux store, it will log full action typesconstuseReduxStore=create(devtools(redux(reducer,initialState)),,{ name,store:storeName3})constuseReduxStore=create(devtools(redux(reducer,initialState)),,{ name,store:storeName4})
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 configureserialize 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 } }).
devtools will only log actions from each separated store unlike in a typicalcombined reducers redux store. See an approach to combining storespmndrs#163
You can log a specific action type for eachset function by passing a third parameter:
constuseBearStore=create(devtools((set)=>({ ...eatFish:()=>set((prev)=>({fishes:prev.fishes>1 ?prev.fishes-1 :0}),false,'bear/eatFish'), ...
You can also log the action's type along with its payload:
...addFishes:(count)=>set((prev)=>({fishes:prev.fishes+count}),false,{type:'bear/addFishes', count,}), ...
If an action type is not provided, it is defaulted to "anonymous". You can customize this default value by providing ananonymousActionType parameter:
devtools(...,{anonymousActionType:'unknown', ...})
If you wish to disable devtools (on production for instance). You can customize this setting by providing theenabled parameter:
devtools(...,{enabled:false, ...})
The store created withcreate 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 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.
import{createContext,useContext}from'react'import{createStore,useStore}from'zustand'conststore=createStore(...)// vanilla store without hooksconstStoreContext=createContext()constApp=()=>(<StoreContext.Providervalue={store}> ...</StoreContext.Provider>)constComponent=()=>{conststore=useContext(StoreContext)constslice=useStore(store,selector)...
Basic typescript usage doesn't require anything special except for writingcreate<State>()(...) instead ofcreate(...)...
import{create}from'zustand'import{devtools,persist}from'zustand/middleware'importtype{}from'@redux-devtools/extension'// required for devtools typinginterfaceBearState{bears:numberincrease:(by:number)=>void}constuseBearStore=create<BearState>()(devtools(persist((set)=>({bears:0,increase:(by)=>set((state)=>({bears:state.bears+by})),}),{name:'bear-storage',},),),)
A more complete TypeScript guide ishere.
- You may wonder how to organize your code for better maintenance:Splitting the store into separate slices.
- Recommended usage for this unopinionated library:Flux inspired practice.
- Calling actions outside a React event handler in pre-React 18.
- Testing
- For more, have a lookin the docs folder
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, visitthe doc.
About
🐻 Bear necessities for state management in React
Resources
License
Contributing
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
Packages0
Languages
- TypeScript97.5%
- JavaScript2.5%
