How to Use Zustand in React: Simple State Management Guide
To use
zustand in React, first create a store with create that holds your state and actions. Then, use the custom hook from the store inside your components to read and update state easily.Syntax
Zustand uses a create function to make a store. This store holds state and functions to change it. You use a hook from the store inside React components to get or set state.
create: Makes the store.- State object: Holds your data.
- Actions: Functions to update state.
- Hook: Used in components to access state.
javascript
import create from 'zustand' const useStore = create(set => ({ count: 0, increase: () => set(state => ({ count: state.count + 1 })), decrease: () => set(state => ({ count: state.count - 1 })) }))
Example
This example shows a simple counter using Zustand. The store holds the count and two actions to increase or decrease it. The React component uses the store hook to read and update the count.
javascript
import React from 'react' import create from 'zustand' const useStore = create(set => ({ count: 0, increase: () => set(state => ({ count: state.count + 1 })), decrease: () => set(state => ({ count: state.count - 1 })) })) export default function Counter() { const { count, increase, decrease } = useStore() return ( <div> <h1>Count: {count}</h1> <button onClick={increase}>Increase</button> <button onClick={decrease}>Decrease</button> </div> ) }
Output
Count: 0
[Increase] [Decrease]
Clicking Increase adds 1 to count.
Clicking Decrease subtracts 1 from count.
Common Pitfalls
Common mistakes when using Zustand include:
- Not calling the store hook inside a React component or custom hook, which breaks React rules.
- Mutating state directly instead of using the
setfunction, which prevents updates. - Forgetting to return a new state object inside
set, causing no re-render.
Always use the set updater function and treat state as immutable.
javascript
/* Wrong way: mutating state directly */ const useStore = create(set => ({ count: 0, increase: () => { // This does NOT update state correctly // state.count += 1 // WRONG } })) /* Right way: use set with new state */ const useStore = create(set => ({ count: 0, increase: () => set(state => ({ count: state.count + 1 })) }))
Quick Reference
Remember these key points when using Zustand:
- Create store: Use
createwith state and actions. - Use hook: Call the store hook inside components to access state.
- Update state: Use
setwith a new state object. - Keep state immutable: Never change state directly.
- Works well: For simple to medium state needs without boilerplate.
Key Takeaways
Use
create from zustand to make a store with state and actions.Access and update state inside React components using the store hook.
Always update state immutably using the
set function.Do not call the store hook outside React components or custom hooks.
Zustand is simple and minimal for state management without boilerplate.