- Notifications
You must be signed in to change notification settings - Fork0
🐻 Bear necessities for state management in React
License
Aslemammad/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 to deal 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 install zustand# or yarn add zustandYour store is a hook! You can put anything in it: primitives, objects, functions. Theset functionmerges state.
importcreatefrom'zustand'constuseStore=create(set=>({bears:0,increasePopulation:()=>set(state=>({bears:state.bears+1})),removeAllBears:()=>set({bears:0})}))
Use the hook anywhere, no providers needed. Select your state and the component will re-render on changes.
functionBearCounter(){constbears=useStore(state=>state.bears)return<h1>{bears} around here ...</h1>}functionControls(){constincreasePopulation=useStore(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=useStore()
It detects changes with strict-equality (old === new) by default, this is efficient for atomic state picks.
constnuts=useStore(state=>state.nuts)consthoney=useStore(state=>state.honey)
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 theshallow equality function.
importshallowfrom'zustand/shallow'// Object pick, re-renders the component when either state.nuts or state.honey changeconst{ nuts, honey}=useStore(state=>({nuts:state.nuts,honey:state.honey}),shallow)// Array pick, re-renders the component when either state.nuts or state.honey changeconst[nuts,honey]=useStore(state=>[state.nuts,state.honey],shallow)// Mapped picks, re-renders the component when state.treats changes in order, count or keysconsttreats=useStore(state=>Object.keys(state.treats),shallow)
For more control over re-rendering, you may provide any custom equality function.
consttreats=useStore(state=>state.treats,(oldTreats,newTreats)=>compare(oldTreats,newTreats))
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.
constfruit=useStore(useCallback(state=>state.fruits[id],[id]))
If a selector doesn't depend on scope, you can define it outside the render function to obtain a fixed reference without useCallback.
constselector=state=>state.berriesfunctionComponent(){constberries=useStore(selector)
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"constuseStore=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.
constuseStore=create(set=>({fishies:{},fetch:asyncpond=>{constresponse=awaitfetch(pond)set({fishies:awaitresponse.json()})}}))
set allows fn-updatesset(state => result), but you still have access to state outside of it throughget.
constuseStore=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.
constuseStore=create(()=>({paw:true,snout:true,fur:true}))// Getting non-reactive fresh stateconstpaw=useStore.getState().paw// Listening to all changes, fires on every changeconstunsub1=useStore.subscribe(console.log)// Listening to selected changes, in this case when "paw" changesconstunsub2=useStore.subscribe(console.log,state=>state.paw)// Subscribe also supports an optional equality functionconstunsub3=useStore.subscribe(console.log,state=>[state.paw,state.fur],shallow)// Subscribe also exposes the previous valueconstunsub4=useStore.subscribe((paw,previousPaw)=>console.log(paw,previousPaw),state=>state.paw)// Updating state, will trigger listenersuseStore.setState({paw:false})// Unsubscribe listenersunsub1()unsub2()unsub3()unsub4()// Destroying the store (removing all listeners)useStore.destroy()// You can of course use the hook as you always wouldfunctionComponent(){constpaw=useStore(state=>state.paw)
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.
importcreatefrom'zustand/vanilla'conststore=create(()=>({ ...}))const{ getState, setState, subscribe, destroy}=store
You can even consume an existing vanilla store with React:
importcreatefrom'zustand'importvanillaStorefrom'./vanillaStore'constuseStore=create(vanillaStore)
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.
constuseStore=create(set=>({scratches:0, ...}))functionComponent(){// Fetch initial stateconstscratchRef=useRef(useStore.getState().scratches)// Connect to the store on mount, disconnect on unmount, catch state-changes in a referenceuseEffect(()=>useStore.subscribe(scratches=>(scratchRef.current=scratches),state=>state.scratches),[])
Reducing nested structures is tiresome. Have you triedimmer?
importproducefrom'immer'constuseStore=create(set=>({lush:{forest:{contains:{a:"bear"}}},clearForest:()=>set(produce(state=>{state.lush.forest.contains=null}))}))constclearForest=useStore(state=>state.clearForest)clearForest();
You can functionally compose your store any way you like.
// Log every time state is changedconstlog=config=>(set,get,api)=>config(args=>{console.log(" applying",args)set(args)console.log(" new state",get())},get,api)// Turn the set method into an immer proxyconstimmer=config=>(set,get,api)=>config((partial,replace)=>{constnextState=typeofpartial==='function' ?produce(partial) :partialreturnset(nextState,replace)},get,api)constuseStore=create(log(immer((set)=>({bees:false,setBees:(input)=>set((state)=>void(state.bees=input)),})),),)
How to pipe middlewares
importcreatefrom"zustand"importproducefrom"immer"importpipefrom"ramda/es/pipe"/* log and immer functions from previous example *//* you can pipe as many middlewares as you want */constcreateStore=pipe(log,immer,create)constuseStore=createStore(set=>({bears:1,increasePopulation:()=>set(state=>({bears:state.bears+1}))}))exportdefaultuseStore
For a TS example see the followingdiscussion
How to type immer middleware in TypeScript
import{State,StateCreator}from'zustand'importproduce,{Draft}from'immer'constimmer=<TextendsState>(config:StateCreator<T>):StateCreator<T>=>(set,get,api)=>config((partial,replace)=>{constnextState=typeofpartial==='function' ?produce(partialas(state:Draft<T>)=>T) :partialasTreturnset(nextState,replace)},get,api)
You can persist your store's data using any kind of storage.
importcreatefrom"zustand"import{persist}from"zustand/middleware"exportconstuseStore=create(persist((set,get)=>({fishes:0,addAFish:()=>set({fishes:get().fishes+1})}),{name:"food-storage",// unique namegetStorage:()=>sessionStorage,// (optional) by default the 'localStorage' is used}))
How to use custom storage engines
You can use other storage methods outside oflocalStorage andsessionStorage by defining your ownStateStorage. A customStateStorage object also allows you to write middlware for the persisted store when getting or setting store data.
importcreatefrom"zustand"import{persist,StateStorage}from"zustand/middleware"import{get,set}from'idb-keyval'// can use anything: IndexedDB, Ionic Storage, etc.// Custom storage objectconststorage:StateStorage={getItem:async(name:string):Promise<string|null>=>{console.log(name,"has been retrieved");returnawaitget(name)||null},setItem:async(name:string,value:string):Promise<void>=>{console.log(name,"with value",value,"has been saved");set(name,value)}}exportconstuseStore=create(persist((set,get)=>({fishes:0,addAFish:()=>set({fishes:get().fishes+1})}),{name:"food-storage",// unique namegetStorage:()=>storage,}))
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}}}constuseStore=create(set=>({grumpiness:0,dispatch:args=>set(state=>reducer(state,args)),}))constdispatch=useStore(state=>state.dispatch)dispatch({type:types.increase,by:2})
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. Trythis example.
import{redux}from'zustand/middleware'constuseStore=create(redux(reducer,initialState))
Because React handlessetState 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 inunstable_batchedUpdates
import{unstable_batchedUpdates}from'react-dom'// or 'react-native'constuseStore=create((set)=>({fishes:0,increaseFishes:()=>set((prev)=>({fishes:prev.fishes+1}))}))constnonReactCallback=()=>{unstable_batchedUpdates(()=>{useStore.getState().increaseFishes()})}
More details:pmndrs#302
import{devtools}from'zustand/middleware'// Usage with a plain action store, it will log actions as "setState"constuseStore=create(devtools(store))// Usage with a redux store, it will log full action typesconstuseStore=create(devtools(redux(reducer,initialState)))
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(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 typicalcombined reducers redux store. See an approach to combining storespmndrs#163
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 store is a hook, passing it as a normal context value may violate rules of hooks. To avoid misusage, a specialcreateContext is provided.
importcreatefrom'zustand'importcreateContextfrom'zustand/context'const{ Provider, useStore}=createContext()constcreateStore=()=>create(...)constApp=()=>(<ProvidercreateStore={createStore}> ...</Provider>)constComponent=()=>{conststate=useStore()constslice=useStore(selector)...}
createContext usage in real components
importcreatefrom"zustand";importcreateContextfrom"zustand/context";// Best practice: You can move the below createContext() and createStore to a separate file(store.js) and import the Provider, useStore here/wherever you need.const{ Provider, useStore}=createContext();constcreateStore=()=>create((set)=>({bears:0,increasePopulation:()=>set((state)=>({bears:state.bears+1})),removeAllBears:()=>set({bears:0})}));constButton=()=>{return({/** store() - This will create a store for each time using the Button component instead of using one store for all components **/}<ProvidercreateStore={createStore}><ButtonChild/></Provider>);};constButtonChild=()=>{conststate=useStore();return(<div>{state.bears}<buttononClick={()=>{state.increasePopulation();}}> +</button></div>);};exportdefaultfunctionApp(){return(<divclassName="App"><Button/><Button/></div>);}
createContext usage with initialization from props (in TypeScript)
importcreatefrom"zustand";importcreateContextfrom"zustand/context";typeBearState={bears:numberincrease:()=>void}// pass the type to `createContext` rather than to `create`const{ Provider, useStore}=createContext<BearState>();exportdefaultfunctionApp({ initialBears}:{initialBears:number}){return(<ProvidercreateStore={()=>create((set)=>({bears:initialBears,increase:()=>set((state)=>({bears:state.bears+1})),}))}><Button/></Provider>)}
// You can use `type`typeBearState={bears:numberincrease:(by:number)=>void}// Or `interface`interfaceBearState{bears:numberincrease:(by:number)=>void}// And it is going to work for bothconstuseStore=create<BearState>(set=>({bears:0,increase:(by)=>set(state=>({bears:state.bears+by})),}))
Or, usecombine and let tsc infer types. This merges two states shallowly.
import{combine}from'zustand/middleware'constuseStore=create(combine({bears:0},(set)=>({increase:(by:number)=>set((state)=>({bears:state.bears+by}))})),)
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.
For information regarding testing with Zustand, visit the dedicatedWiki page.
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 dedicatedWiki page.
About
🐻 Bear necessities for state management in React
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Packages0
Languages
- TypeScript96.2%
- JavaScript3.7%
- Shell0.1%
