Zustand Basics
Zustand Basics covers lightweight external stores, selector subscriptions, comparing Zustand with Context and Redux Toolkit.
Course: React — State Management Lesson: 07
Learning objectives
Understand Zustand's store model, create a small shared store, read state with selectors, update state through actions, and compare Zustand with Context and Redux Toolkit.
What is Zustand?
Zustand is a lightweight state-management library for React. It allows a store to be created outside the component tree and consumed through a Hook. Components subscribe to the selected state they need.
Install:
npm install zustand
Create a store
import { create } from "zustand";export const useCartStore = create((set) => ({items: [],addItem: (product) =>set((state) => ({ items: [...state.items, product] })),removeItem: (productId) =>set((state) => ({items: state.items.filter(item => item.id !== productId)})),clearCart: () => set({ items: [] })}));
The store contains state and actions. Updates should be immutable, and the set function merges partial state by default.
Consume with selectors
function CartBadge() {const count = useCartStore(state => state.items.length);return <span>Cart: {count}</span>;}function AddButton({ product }) {const addItem = useCartStore(state => state.addItem);return <button onClick={() => addItem(product)}>Add</button>;}
Selecting only the required value can reduce unnecessary subscriptions. Be careful with selectors that create a new object or array on every evaluation; use appropriate shallow comparison or stable selector patterns when needed.
Organize larger stores
For a growing application, keep stores focused by domain rather than creating one enormous store. A store can expose domain actions and selectors while service modules handle HTTP communication.
Async actions
Zustand actions can be asynchronous:
const useProfileStore = create((set) => ({profile: null,status: "idle",loadProfile: async () => {set({ status: "loading" });try {const response = await fetch("/api/profile");if (!response.ok) throw new Error("Profile request failed");const profile = await response.json();set({ profile, status: "success" });} catch (error) {set({ status: "error" });}}}));
For production, keep transport logic in a service and represent error details safely. Consider whether the data is better treated as server state with a dedicated query library.
Zustand compared with other options
useState: simplest for component-local state.- Context: distributes values through a provider subtree.
- Zustand: offers a lightweight external client-state store.
- Redux Toolkit: provides a more structured action/reducer architecture and ecosystem.
- React Query/TanStack Query: focuses on remote server data and caching.
Common mistakes
- Putting all server data into Zustand by default.
- Creating one store with unrelated responsibilities.
- Subscribing components to the entire store unnecessarily.
- Returning unstable composite selector values without considering equality.
- Mixing transport details and UI presentation.
Best practices
Keep stores focused, select only what components need, define domain actions, and use a server-state tool when caching and synchronization are the main problem.
Interview questions & answers
Interview preparation
5 questions grouped by difficulty — expand any card for a model answer and follow-up probe.
Beginner
1What is Zustand?
BeginnerModel answer
A small library for external React stores with a simple Hook-based API and selector subscriptions.
2How does Zustand differ from Context?
BeginnerModel answer
Zustand is an external store with selective subscriptions; Context re-renders consumers when the provider value identity changes.
Intermediate
3How does a component subscribe to a Zustand store?
IntermediateModel answer
By calling the store Hook with an optional selector so it re-renders when the selected slice changes.
4When might Redux Toolkit be preferable?
IntermediateModel answer
When you need stronger conventions, middleware ecosystems, DevTools workflows, or larger-team structure around actions and slices.
Advanced
5Why use selectors?
AdvancedModel answer
Selectors avoid re-rendering on unrelated store updates by subscribing only to needed values.
Practice
Create a cart store with add, remove, quantity update, and clear actions. Build a header badge and cart page that subscribe to different slices of the store.