Skip to content
Shubham JangleResources
React

Explore topics

State Management using zustand

Watch the walkthrough
Open on Instagram

Quick revision

Keep state close to the components that use it. Lift shared state to a common ancestor when that is sufficient. A small external store such as Zustand can reduce prop passing when distant components need the same data or actions.

Store model

create builds a store and its React hook. Store actions call set, using the current state when the next value depends on it. Select the smallest slice a component needs so unrelated updates do not make it subscribe to the entire store.

const votes = useVoteStore(state => state.votes);
const incrementVote = useVoteStore(state => state.incrementVote);

These selectors are an original revision example. The repository's App2.js instead reads whole-store objects. Compare it with App.js, which passes setVotes through several layers, and store.js, which owns the shared values and action.

Design decisions

Keep temporary input drafts local. Do not copy a store value into local state unless you intentionally need a separate draft. Persistence, API caching, and server rendering require their own design; a store alone does not provide them.

Recall check

Which components need the votes value, and which only need the increment action? Subscribe accordingly.

Reference: Zustand's official introduction and selectors.

Supporting material