Skip to content

Volume ITechnology

6.4.8 — Context and Zustand, Step by Step ​

The same shop cart, one more time. On page 6.4.7 you built it with Redux Toolkit. Redux is powerful, but for a small or medium app it is a lot of structure.

This page builds the same cart with the two lighter tools: Context, which ships inside React, and Zustand, a tiny library. You will see exactly what each one costs, what each one gets wrong when pushed too far, and how to choose.

1. The problem both tools solve ​

You already know the problem from page 6.4.3: prop drilling. A value lives at the top, and a component deep inside needs it. Every component in between must carry it as a prop, even though they never use it.

Prop drilling: passed by handApp (owns cart)Layout (ignores it)Sidebar (ignores it)Menu (ignores it)CartButton (uses it)cartpassed throughevery layerContext: read where neededProvider (holds cart)LayoutSidebarMenuCartButton (reads it)useContext
Left: prop drilling. Three components in the middle carry the cart only to hand it on. Right: with context, the component that needs the cart reads it directly from the provider above, and the middle components know nothing about it.

Left: the cart is handed down through Layout, Sidebar and Menu, who do not care about it. If you later rename the prop or add a second value, you must edit every layer. Right: the value is put in one place, and the component that wants it reaches up and takes it directly.

2. Context, step by step ​

Context is React's built-in way to make a value available to a whole part of the tree without passing props. It has three steps: create it, provide a value, read the value.

We start with the best use of Context: something that changes rarely and is needed everywhere, such as the colour theme.

tsx
// src/theme/ThemeContext.tsx
import { createContext, useContext, useState } from 'react'
import type { ReactNode } from 'react'

type Theme = 'light' | 'dark'

type ThemeValue = {
  theme: Theme
  toggleTheme: () => void
}

const ThemeContext = createContext<ThemeValue | null>(null)                        // (1)

export function ThemeProvider({ children }: { children: ReactNode }) {              // (2)
  const [theme, setTheme] = useState<Theme>('light')

  const value: ThemeValue = {
    theme,
    toggleTheme: () => setTheme((t) => (t === 'light' ? 'dark' : 'light')),
  }

  return <ThemeContext value={value}>{children}</ThemeContext>                      // (3)
}

export function useTheme(): ThemeValue {                                            // (4)
  const value = useContext(ThemeContext)
  if (value === null) {
    throw new Error('useTheme must be used inside a ThemeProvider')
  }
  return value
}
  1. createContext makes the context. The argument is the default value, used when a component asks for the context but no provider is above it. We give null on purpose, so that forgetting the provider is detectable.
  2. ThemeProvider is our own component. It owns the real state with useState. Context itself stores nothing. It only carries a value down.
  3. <ThemeContext value={value}> provides the value to everything inside it. (In React 18 and older you wrote <ThemeContext.Provider value={value}>. React 19 allows the shorter form, and the old one still works.) children is "whatever is placed between the opening and closing tags", as on page 6.4.1.
  4. useTheme is a small custom hook (a function that starts with use and calls other hooks) that reads the context and throws a clear error if the provider is missing. Components then call useTheme() and get a value that is never null. Without this, every component would have to check for null.

Use it like this:

tsx
// src/App.tsx
import { ThemeProvider, useTheme } from './theme/ThemeContext'

function ThemeButton() {
  const { theme, toggleTheme } = useTheme()                                         // (1)
  return <button onClick={toggleTheme}>Theme: {theme}</button>
}

export default function App() {
  return (
    <ThemeProvider>                                                                 {/* (2) */}
      <ThemeButton />
    </ThemeProvider>
  )
}
  1. Any component below the provider, at any depth, can call useTheme().
  2. The provider wraps the part of the app that needs the value. Usually it wraps the whole app.

When toggleTheme is called, the provider's state changes, the provider re-renders, it creates a new value, and every component that called useTheme() re-renders with it.

The catch: context cannot select ​

That last sentence is the whole weakness of Context. A component that reads a context re-renders whenever the context's value changes, even if it only uses one small part of it.

Imagine we put the theme and the cart in one context value. A Chart component reads only the theme. A Badge reads only the cart. The customer adds an item, so the value changes, so both re-render. We measured exactly this: after one cart change, the chart that only wanted the theme rendered again.

Context: one value for everyoneProvidervalue = { theme, cart }Headerreads cartChartreads themeBadgereads cartCart changed: all three draw again.The chart did not need to.Selectors: each reads its own pieceStore{ theme, cart }Headerselects cartChartselects themeBadgeselects cartCart changed: only Header and Badge draw again.The chart stays still.Same change, very different amount of work
Left: context re-renders every component that reads it, whatever part it cares about. Right: a selector store re-renders only the components whose selected value changed. Red outline means "draws again".

For a theme, which changes a few times per visit, this does not matter. For a cart, or anything that changes on every keystroke, it adds up. There are three honest ways to deal with it:

  1. Split into several contexts, one per kind of data (ThemeContext, CartContext, UserContext), so a change in one does not wake readers of the others.
  2. Separate the data from the actions. The actions (addItem) never change, but the data does. Put them in two contexts, and a button that only calls addItem will not re-render when the data changes.
  3. Use a store with selectors, which is what Redux and Zustand are.

One more thing people try: useMemo on the value. It helps in one narrow case, which is when the provider's parent re-renders but the value did not really change. It does not stop re-renders caused by the value actually changing.

What Context is good for ​

Context is best at dependency injection: handing a stable dependency to a whole subtree without threading it through props. The classic cases are the colour theme, the current language, the logged-in user, and "which database or API client should I use". These change rarely, and many components need them. For everything that changes often, use a store.

3. Zustand, step by step ​

Zustand (German for "state") is a very small library. You make a store, which is a plain object that holds state and the functions that change it. Then you read from it with a hook. There is no provider, and components can pick exactly the values they need.

Install it:

bash
npm install zustand

Step 1: create the store ​

ts
// src/stores/cartStore.ts
import { create } from 'zustand'

export type CartItem = {
  productId: string
  name: string
  priceCents: number
  quantity: number
}

type CartStore = {
  items: CartItem[]                                                                 // (1)
  addItem: (product: Omit<CartItem, 'quantity'>) => void                            // (2)
  removeItem: (productId: string) => void
  clear: () => void
}

export const useCartStore = create<CartStore>()((set) => ({                         // (3)
  items: [],

  addItem: (product) =>
    set((state) => {                                                                // (4)
      const existing = state.items.find((i) => i.productId === product.productId)
      if (existing) {
        return {
          items: state.items.map((i) =>
            i.productId === product.productId ? { ...i, quantity: i.quantity + 1 } : i,
          ),
        }
      }
      return { items: [...state.items, { ...product, quantity: 1 }] }
    }),

  removeItem: (productId) =>
    set((state) => ({ items: state.items.filter((i) => i.productId !== productId) })),

  clear: () => set({ items: [] }),                                                  // (5)
}))
  1. The data and the actions live side by side in one type. There is no separate "action" object and no reducer. An action is just a function.
  2. Each action is a normal function property.
  3. create makes the store and returns a hook. By convention the name starts with use. The extra () after create<CartStore> is a TypeScript detail that Zustand needs so that it can work out the types of middleware. Write it exactly like this. set is the function that changes the state.
  4. set accepts a function that gets the current state and returns the part you want to change. Zustand merges it into the state. You do not return the whole state, only the fields that change. (This is different from React's useState, whose setter replaces.) You still must not change state in place: build new arrays and objects, as on page 6.4.2.
  5. When the change does not depend on the old state, pass an object directly.

Compare this with page 6.4.7: no Provider, no configureStore, no typed hooks, no action types. It is about a third of the code.

Step 2: use it in components ​

tsx
// src/components/Header.tsx
import { useCartStore } from '../stores/cartStore'

export function Header() {
  const itemCount = useCartStore((state) =>
    state.items.reduce((sum, i) => sum + i.quantity, 0),                           // (1)
  )
  return <header>My Shop · Cart: {itemCount}</header>
}
tsx
// src/components/ProductCard.tsx
import { useCartStore } from '../stores/cartStore'

type Product = { id: string; name: string; priceCents: number }

export function ProductCard({ product }: { product: Product }) {
  const addItem = useCartStore((state) => state.addItem)                           // (2)

  return (
    <article>
      <h2>{product.name}</h2>
      <button
        onClick={() =>
          addItem({ productId: product.id, name: product.name, priceCents: product.priceCents })
        }
      >
        Add to cart
      </button>
    </article>
  )
}
  1. The function you pass to the hook is a selector, exactly as in Redux. The component re-renders only when the value it returns changes.
  2. ProductCard selects only the addItem function. That function never changes, so ProductCard never re-renders because of the cart. We measured it: when the cart changed, a component that selected the theme rendered zero extra times and the badge rendered once.

Nothing wraps the app. You can import the hook anywhere and it works.

The one trap: selecting an object ​

In Zustand 5, this looks natural and is a bug:

tsx
// Wrong: returns a NEW object on every call
const { items, clear } = useCartStore((state) => ({ items: state.items, clear: state.clear }))

Zustand decides whether to re-render by comparing the selector's result with ===. A fresh object is never === the last one, so it always looks changed. In version 5 this is not just slow: React ends up in a loop and throws "Maximum update depth exceeded". We reproduced that error.

There are two fixes. The simple one is to select each value on its own line:

tsx
const items = useCartStore((state) => state.items)
const clear = useCartStore((state) => state.clear)

The other is useShallow, which compares the fields of the returned object one by one instead of the object itself:

tsx
import { useShallow } from 'zustand/react/shallow'

const { items, clear } = useCartStore(useShallow((state) => ({ items: state.items, clear: state.clear })))

Step 3: use it outside React ​

The store is an ordinary object, so code that is not a component can use it. This is something Redux makes harder and Context cannot do at all.

ts
// src/lib/socket.ts
import { useCartStore } from '../stores/cartStore'

export function onCartChangedElsewhere(productId: string) {
  useCartStore.getState().addItem({ productId, name: 'Synced item', priceCents: 0 })   // (1)
}

const unsubscribe = useCartStore.subscribe((state, previous) => {                       // (2)
  console.log(`cart items: ${previous.items.length} → ${state.items.length}`)
})
// call unsubscribe() when you no longer want to listen
  1. getState() reads the current state, and the actions inside it work too. Handy for a WebSocket message or a timer.
  2. subscribe calls your function after every change, with the new and the previous state. In our run, adding one product printed cart items: 1 → 2.

Use this sparingly. It is easy to make a mess if every file changes the store, so keep real changes inside the store's own actions.

Step 4: save the state across page reloads ​

The cart should still be there if the customer refreshes the page. Zustand's persist middleware does it. (A middleware is a wrapper around the store that adds a feature.)

ts
// src/stores/cartStore.ts (persisted version)
import { create } from 'zustand'
import { persist } from 'zustand/middleware'

type CartItem = { productId: string; name: string; priceCents: number; quantity: number }
type CartStore = { items: CartItem[]; clear: () => void }

export const useCartStore = create<CartStore>()(
  persist(
    (set) => ({
      items: [],
      clear: () => set({ items: [] }),
    }),
    {
      name: 'cart',                                                                 // (1)
      partialize: (state) => ({ items: state.items }),                              // (2)
    },
  ),
)
  1. name is the key in the browser's localStorage (a small key-value store that survives reloads).
  2. partialize chooses what to save. We save only the data, not the functions. We checked what lands in storage: {"state":{"n":2},"version":0}, a plain JSON object with a version number.

Two warnings, both explained in page 6.4.6. A persisted store can cause a "hydration mismatch" if the page is rendered on a server, because the server has no localStorage. And a store defined at module level on a server is shared between visitors. If you build with a framework that renders on a server (Chapter 6.5), read those sections first.

4. The same cart in three tools ​

ContextRedux ToolkitZustand
Amount of code for the cartmoderatemost (several files)least (one file)
Needs a Provideryesyesno
Re-renders only what changednoyesyes
Works outside componentsnoyes (store.dispatch)yes (getState)
Debug toolReact DevToolsRedux DevTools (time travel)Redux DevTools (optional)
Learning curveloweststeepestlow

And how to choose:

  • Theme, language, current user, an API client: Context. It changes rarely, and it is already in React.
  • A cart, a shopping filter, a drawer being open, anything that changes often and many components read: a store. Zustand for most apps.
  • A large app with many teams that wants one strict pattern and a visible action log: Redux Toolkit.
  • Products, orders, anything that lives on a server: none of these. Use TanStack Query (pages 6.4.10 and 6.4.11).
  • What page you are on, the current filter, the sort order: the URL (pages 6.4.9 and 6.4.12).

Most apps use two or three of these together. That is normal.

What the interviewer will push on ​

"What is Context for, and when does it hurt performance?" It carries a value down the tree without props. Every component that reads it re-renders when the value changes, and a component cannot read only part of it. So it suits rarely changing values, and hurts for fast-changing ones. Add the fixes: split contexts, separate actions from data, or use a store with selectors.

"What is prop drilling, and how do you avoid it?" Passing a value through layers that do not use it. Fix by lifting less, composing with children, Context, or a store. Naming children composition shows you are not reaching for global state by reflex.

"How is Zustand different from Redux?" No provider, no reducers or action types, state and actions in one object, selectors for fine-grained updates. Less structure and less tooling. Redux gives a strict pattern and strong DevTools. They both use the same React hook underneath (useSyncExternalStore, page 6.4.5), which makes them safe with concurrent rendering.

"Why does my Zustand component loop forever?" A selector that returns a new object every time (in version 5). Select single values, or use useShallow.

"Where do you keep server data: Context, Redux or Zustand?" In none of them. In a server-data cache such as TanStack Query. This answer is what the question is checking.

"How would you persist state?" The persist middleware, with partialize to save only the data. Then mention the server-rendering hydration issue.

One thing to volunteer: say that you would first try to keep the state local, then lift it, and only then reach for Context or a store. It signals that you do not use global state as a default.

Recall

  • Prop drilling is passing a value through layers that do not use it. Context and stores remove it.
  • Context in three steps: createContext(default) → a provider component that owns the state and renders <Ctx value={…}> → components call useContext(Ctx). Wrap useContext in a custom hook that throws if the provider is missing.
  • Context cannot select. Every reader re-renders when the value changes. Fine for the theme, language, user. Bad for fast-changing data. Fixes: split contexts, separate actions from data, or use a store.
  • Zustand: create<State>()((set) => ({ data, actions })) returns a hook. set merges the fields you return. No provider. Read with a selector: useStore((s) => s.items). Only components whose selected value changed re-render.
  • Zustand 5 trap: a selector that returns a new object each time loops with "Maximum update depth exceeded". Select values separately, or wrap with useShallow.
  • Outside React: store.getState() and store.subscribe(fn).
  • persist middleware saves to localStorage. partialize picks what to save. Beware the server hydration mismatch.
  • Choosing: rarely changing values → Context. Frequently changing shared client state → Zustand (or Redux Toolkit for big, strict teams). Server data → TanStack Query. Page, filter, sort → the URL.

Self-test: Why does a chart that only reads the theme redraw when the cart changes, with one shared context? · What does set do with the object you return? · Why does useCartStore((s) => ({ a: s.a })) break in version 5? · Name two things Zustand can do that Context cannot. · Where does a product list belong?

Next: 6.4.9 is about the one piece of state every web app has and which does not belong in a store: which page the user is looking at. It teaches React Router, step by step.

Combine chapters into one PDF

Pick the chapters you want. They print in the order you pick them.

Volume I — Technology
Part 0 — Retention & Notation
Part 1 — Foundations of Computation
Part 2 — Operating Systems
2.1 The Kernel
2.2 Processes
2.3 Threads & Scheduling
2.4 Concurrency Under the Hood
2.5 Memory Management
2.6 File Systems
2.7 Input/Output
2.8 Linux for Engineers
2.9 Windows & macOS in Practice
Part 3 — Languages, Compilers & Runtimes
3.6 JavaScript & V8
3.7 TypeScript
3.8 Node.js Internals
3.13 Python & CPython
3.14 FastAPI & Production Python
Part 4 — Data Structures & Algorithms
4.0 Classic Problems — Before NeetCode
4.4 Arrays & Hashing — Problems
4.5 Two Pointers
4.6 Sliding Window
4.8 Stack — Problems
4.9 Linked List — Problems
4.11 Binary Search — Problems
4.13 Trees
4.14 Tree — Problems
4.15 Trie — Problems
4.17 Heap — Problems
4.18 Backtracking — Problems
4.19 Graphs
4.20 Graph — Problems
4.21 Advanced Graph — Problems
4.23 1-D DP — Problems
4.24 2-D DP — Problems
4.26 Greedy — Problems
4.27 Interval — Problems
4.28 Math & Geometry — Problems
4.30 Bit Manipulation — Problems
Part 5 — Networking & the Web
5.3 IP
5.4 Transport
5.6 HTTP
Part 6 — Frontend Engineering
6.1 Browser Internals
6.2 HTML & CSS Mastery
6.3 JavaScript in the Browser
6.4 React, from First Component to Full Shop
6.5 Frameworks & Rendering
6.8 UI Engineering & Patterns
Part 7 — Databases & Storage
7.2 SQL Mastery
7.3 Storage Engine Internals
7.4 Transactions
7.5 NoSQL Taxonomy
7.8 Analytics & Big Data
Part 8 — Security, Identity & Cryptography
8.2 Cryptography
8.3 Protocols of Trust
8.4 Identity: AuthN & AuthZ
8.5 Application Security
8.6 Infrastructure Security
Part 9 — Software Design (LLD)
9.2 OOP Foundations
9.3 Design Principles
9.4 Design Patterns
9.5 Concurrency
9.6 API Design
9.7 LLD Interview Machines
9.9 Node/Express Production Playbook
Part 10 — Distributed Systems & HLD
10.7 Consistency & Consensus
10.8 Messaging & Microservices
10.14 Caching
Building blocks from the design seat
Part 11 — System Design Case Studies
Part 12 — AI & ML Engineering
12.1 What AI Engineering Is
12.2 The Math You Need
12.3 Classical Machine Learning
12.4 Data for ML
12.5 Deep Learning
12.6 Embeddings & Vector Search
12.7 Transformers & LLMs
12.8 Building with LLMs
12.9 Retrieval-Augmented Generation
12.10 Agents
12.11 Adapting Models
12.12 Production AI
12.13 Multimodal AI
12.14 AI Security & Governance
12.15 Case Studies & Capstone
Part 13 — Cloud, DevOps & Infrastructure
13.11 Git, from First Commit to Team Workflow
Part 14 — Containers: Docker & Kubernetes
14.1 Foundations
14.2 Docker
14.3 Kubernetes
14.4 Kubernetes on Azure
Part 15 — The Craft & Career
Nothing picked yet