Skip to main content

zustand (React)

Build Size Version

Step 1: Install

npm install zustand # or yarn add zustand

Step 2: Store Initialization

The created store is a hook, you can put anything in it: basic variables, objects, functions, state must be updated immutably, set function merges state to achieve state update.

import { create } from 'zustand'

const useBearStore = create((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 })),
removeAllBears: () => set({ bears: 0 }),
}))

Step 3: Store binds the component and it's done!

Hooks can be used anywhere, no provider required。
Get your target state based on the selector and the component will re-render on state change。

Get target state:bears
function BearCounter() {
const bears = useBearStore((state) => state.bears)
return <h1>{bears} around here ...</h1>
}
Update target state:bears
function Controls() {
const increasePopulation = useBearStore((state) => state.increasePopulation)
return <button onClick={increasePopulation}>one up</button>
}