IE, Since set(() => ({bears: {a: 0})) is shallowly merged, it would override other parts of {bears} so you would need set((state) => ({bears: {...state.bears, a: 0}}))
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()
Persist Middleware
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 }, ),)
Could autogenerate selectors to turn const bears = useBearStore((state) => state.bears) into the much? better const bears = useBearStore.use.bears()