Sub topic 1
Why Zustand and when to reach for it
Zustand is a small state-management library for React. A Zustand store holds shared state and the actions that change it. Components read that state through selectors, which are functions that choose part of the store.
Prerequisites
This chapter assumes React function components, hooks, JavaScript or TypeScript modules, object spread, and immutable updates. You should also understand why shared state can become difficult to pass through many component layers.
Why Zustand and when to reach for it
Local useState is usually best when state belongs to one component or a small subtree. Zustand fits when several unrelated components need the same state, when prop drilling becomes noisy, or when update logic should live outside the component that displays it.
Compared with Context alone, Zustand separates reading from the provider tree and gives components selective subscriptions. Compared with a larger state framework, it usually requires less setup. That simplicity does not replace design: define clear actions, keep state minimal, and avoid making every value global.
Your first store with create
create builds a store and returns a React hook. The state creator receives set, a function that applies updates. An action is simply a function stored alongside the data.
import { create } from 'zustand'
interface CounterState {
count: number
increment: () => void
reset: () => void
}
export const useCounterStore = create<CounterState>()((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
reset: () => set({ count: 0 }),
}))The create<CounterState>()(...) form gives the store its TypeScript shape. set merges the returned object into the current state, so an update to count does not remove the actions.
Reading state with selectors
A selector receives the complete state and returns the value a component needs.
function Count() {
const count = useCounterStore((state) => state.count)
return <p>Count: {count}</p>
}
function Controls() {
const increment = useCounterStore((state) => state.increment)
return <button onClick={increment}>Add one</button>
}Each component subscribes to its selected value. Controls does not need to re-render when only count changes. Selecting the whole store defeats this benefit and makes the component respond to unrelated changes.
Updating state with set and actions
Prefer actions for updates. Use a functional update when the next value depends on the current value, as increment does. Direct objects work for fixed values, as reset does.
Exercise
Why does increment use set((state) => ...) instead of set({ count: count + 1 })?
Show answer
The functional form reads the latest store state, so the update remains correct when multiple updates are scheduled close together.