State Management Patterns — React

Keep state as close as possible to the components that use it. Local useState for one component. Lifting state up to the nearest parent for 2 to 3 components…

What's in the shopping cart, the dark theme, the text in a search box, the user who's logged in: all of it is state. But not all of it belongs in the same place.

Deciding where each piece of state lives, and who may read and change it, is called state management. The practical rule is simple: keep state as close as possible to the components that use it, and move it further away only when you need to. It's like an office. A personal note is fine on a sticky note on your desk. A number that two people on one team use goes on the team whiteboard, and the team lead holds the marker. An announcement for the whole building is made through the speakers, and everyone in the building hears it. When there are many announcements and they come often, the office uses a subscription board: each person is only told about the topics they follow. In React, the sticky note is local useState, and the team whiteboard is state kept in a parent (the team lead). The speaker is Context, and the subscription board is a store with selectors. Stores and selectors are explained below.

The ladder: start with the closest step

Read this table like a ladder. Each row is one step, starting from the first row, the place closest to the component:

Where the state lives Used by Example Tool
Local 1 component a search field's text, a menu that is open or closed useState in that component
Lifting state up 2 to 3 nearby components the number Counter and Total use state in the nearest parent, passed down as props
Context many components at many levels, rarely changes theme, the logged-in user, language createContext and useContext, often with useReducer
Store global state that is complex, changes often, and is read by many components a shopping cart a library such as Zustand or Redux Toolkit

Climb to the next row only when the row before it starts to cause trouble. Counter and Total only need lifting state up: keep the number in their parent, then pass it to both as props. No library needed.

A store is a place for state outside every component, provided by a library. A store library is for global state that is complex and used by many components at different levels, to the point where Context feels heavy. Data from a server (the result of a fetch to an API) is a different case. That data is usually handled by a fetching library such as TanStack Query, not copied into a store.

useReducer + Context: one source for many components

In this example, App keeps the theme with useReducer, then shares it through a context with ThemeDisplay:

const ThemeContext = createContext()

function themeReducer(state, action) {
  if (action.type === "toggle") {
    return { theme: state.theme === "dark" ? "light" : "dark" }
  }
  return state
}

function ThemeDisplay() {
  const { state } = useContext(ThemeContext)
  return <p id="theme">{state.theme}</p>
}

function App() {
  const [state, dispatch] = useReducer(themeReducer, { theme: "dark" })
  return (
    <ThemeContext.Provider value={{ state, dispatch }}>
      <ThemeDisplay />
    </ThemeContext.Provider>
  )
}

For a to-do list, the pattern is the same. A reducer with an add action returns a new array [...state, action.payload], where action.payload holds the text of the new to-do. TodoList reads the state from TodoContext, then makes one <li> per item in the state with map:

function TodoList() {
  const { state } = useContext(TodoContext)
  return (
    <ul id="todos">
      {state.map((todo, i) => <li key={i}>{todo}</li>)}
    </ul>
  )
}

Here key={i} is safe: to-dos are only added at the end, never deleted or reordered.

In the second exercise, AddTodo is already there: an input (its text is in the state text) and a button. The button calls dispatch({ type: "add", payload: text }), then setText("") so the input is empty again.

Who re-renders too

Where the state lives decides which components re-render when it changes. Take a small shop: App holds Header (shows how many items are in the cart), Product (the Add button), Sidebar and Footer. Click Add once:

The cart lives in Re-rendered on every click Number of components
State in App (lifting) App, Header, Product, Sidebar, Footer 5
Context (CartProvider with useReducer) CartProvider, Header, Product 3
Two contexts: the cart and dispatch kept apart CartProvider, Header 2
A store with selectors Header 1

This is the two-context version. cartReducer adds 1 for each add action:

const CartContext = createContext(0)
const CartDispatchContext = createContext(null)

function CartProvider({ children }) {
  const [count, dispatch] = useReducer(cartReducer, 0)
  return (
    <CartContext.Provider value={count}>
      <CartDispatchContext.Provider value={dispatch}>
        {children}
      </CartDispatchContext.Provider>
    </CartContext.Provider>
  )
}

// Header: const count = useContext(CartContext)
// Product: const dispatch = useContext(CartDispatchContext)

The dispatch from useReducer is the same function on every render. So Product, which reads only CartDispatchContext, does not re-render when count changes.

The most compact store for React is Zustand:

import { create } from "zustand"

const useCart = create((set) => ({
  count: 0,
  add: () => set((s) => ({ count: s.count + 1 })),
}))

function Header() {
  const count = useCart((s) => s.count) // re-renders only when count changes
  return <span>Cart: {count}</span>
}

function Product() {
  const add = useCart((s) => s.add) // always the same function
  return <button onClick={add}>Add</button>
}

Another popular library is Redux (written today with Redux Toolkit), used a lot in big projects with big teams. There are also Jotai and MobX.

⚠️ Using a store too soon, and Context that re-renders everyone

TL;DR: Keep state as close as possible to the components that use it. Local useState for one component. Lifting state up to the nearest parent for 2 to 3 components. Context (often with useReducer) for data read by many components that rarely changes. A store (a place for state outside every component, from a library such as Zustand or Redux) for global state that is complex and changes often. createContext makes the context, useReducer keeps the state, and <Context.Provider value={{ state, dispatch }}> shares it without props. useContext reads it. When the context value changes, every component that calls useContext re-renders. A store with selectors (functions that pick the part of the store a component reads) only re-renders the components that read the part that changed. Don't rush to a library.

⚡ Start from the closest place

Meaning: State management means deciding where each piece of state lives. Start from the place closest to the components that use it. For one component, use local useState. For 2 to 3 nearby components, use lifting state up (keeping the state in the nearest parent). For many components whose data rarely changes, use Context. For global state that is complex and changes often, there is a store (a place for state outside every component) from a library such as Zustand or Redux Toolkit. Move to the next place only when the place before it starts to cause trouble.

⚡ useReducer + Context

Write:

function App() {
  const [state, dispatch] = useReducer(themeReducer, { theme: "dark" })
  return (
    <ThemeContext.Provider value={{ state, dispatch }}>
      <ThemeDisplay />
    </ThemeContext.Provider>
  )
}

Meaning: useReducer holds the theme state, with the starting state { theme: "dark" }. ThemeContext is a context made with createContext(). The Provider shares { state, dispatch } with every component inside it, such as ThemeDisplay. That component reads them with useContext(ThemeContext), without props.

⚡ A store with selectors

Write:

const useCart = create((set) => ({
  count: 0,
  add: () => set((s) => ({ count: s.count + 1 })),
}))
Guess first: which two state management libraries are popular for React?

Redux (written with Redux Toolkit these days) and Zustand. The example above uses Zustand.

Meaning: create from Zustand makes a store and its hook, useCart, with no Provider. add increases count by one through set. Each component picks the part it reads with a selector, for example (s) => s.count in useCart((s) => s.count). That component only re-renders when that part changes.

What you will learn