React Tutorial 0/120 lessons ~6 min read Lesson 67

    Zustand Basics

    Zustand Basics covers lightweight external stores, selector subscriptions, comparing Zustand with Context and Redux Toolkit.

    Course progress0%
    Focus
    11 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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:

    bash
    npm install zustand

    Create a store

    javascript
    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

    javascript
    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:

    javascript
    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

    2
    1. 1What is Zustand?
      Beginner

      Model answer

      A small library for external React stores with a simple Hook-based API and selector subscriptions.

    2. 2How does Zustand differ from Context?
      Beginner

      Model answer

      Zustand is an external store with selective subscriptions; Context re-renders consumers when the provider value identity changes.

    Intermediate

    2
    1. 3How does a component subscribe to a Zustand store?
      Intermediate

      Model answer

      By calling the store Hook with an optional selector so it re-renders when the selected slice changes.

    2. 4When might Redux Toolkit be preferable?
      Intermediate

      Model answer

      When you need stronger conventions, middleware ecosystems, DevTools workflows, or larger-team structure around actions and slices.

    Advanced

    1
    1. 5Why use selectors?
      Advanced

      Model 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.

    Ready to mark this lesson complete?Track your journey across the entire course.