Skip to content
Visual explainer 4h to learn 4 steps

Context, reducers & shared state

Share state across a tree with context and useReducer without prop drilling.

By Invicly Tech, , in Frontend with React & Next.js. About 11 minutes to read.

Topic 17 of 36

In short

Context passes a value deep into the component tree without threading props through every level. useReducer centralises complex state changes in one pure function, and the two combine well for app-wide state.

Explained simply

Imagine the logged-in user's name is needed by the header, a sidebar and a comment box, each many levels deep. Passing it as a prop through every component in between is called prop drilling. It is tiring and makes the middle components carry data they never use.

Context solves this. A parent component provides a value, and any component below it can read that value directly with useContext or use, no matter how deep it is. Themes, the current user, the language and a shopping cart are typical examples.

useReducer is a different tool that pairs well with context. Instead of many setState calls spread around, you describe what happened with an action, like add item, and one function called a reducer decides the new state. All the update rules live in one place.

Together they give you simple app-wide state: the reducer holds the logic, and context makes the state and the dispatch function available everywhere in the tree, without any extra library.

Press Play on a diagram to walk through it one step at a time.

MapContext skips the middle layers
CartProvider (value)
  • Layout
    • Header uses useCart
    • Sidebar
  • ProductPage
    • AddButton uses useCart
  • CheckoutPage
    • Summary uses useCart
FlowuseReducer update flow
  1. Step 1
    dispatch(action)

    e.g. { type: 'add', item }

  2. Step 2
    reducer(state, action)

    Pure function returns the next state

  3. Step 3
    New state

    React stores it and re-renders consumers

SequenceAdding an item to a context-based cart
AddButton
CartProvider
reducer
CartBadge
  1. 1dispatch({ type: "item_added", id })
    AddButton to CartProvider: dispatch({ type: "item_added", id })
  2. 2reducer(state, action)
    CartProvider to reducer: reducer(state, action)
  3. 3returns a new state object
    reducer to CartProvider: returns a new state object
  4. 4new context value
    CartProvider to CartBadge: new context value
  5. 5re-renders with count + 1
    CartBadge to CartBadge: re-renders with count + 1

In depth

How a component finds its context value

createContext(defaultValue) makes a context object. A provider wraps part of the tree and sets the value; in React 19 you can render the context itself as the provider, and the older Context.Provider form still works. When a component reads the context, React walks up the tree and uses the value from the nearest provider above it. If there is none, it gets the default value.

Providers can be nested, so an inner provider overrides an outer one for its subtree, which is handy for a dark section inside a light page. React 19 also lets you read context with use(MyContext). Unlike useContext, use may be called inside if statements and loops, but still only in components and hooks.

LayersNearest provider wins
  1. 1
    ThemeContext provider: "light"

    Wraps the whole app

  2. 2
    Page components

    Read "light"

  3. 3
    ThemeContext provider: "dark"

    Wraps only the footer

  4. 4
    Footer components

    Read "dark", the nearest value

The re-render cost and how to contain it

When a provider's value changes (compared with Object.is), every component that reads that context re-renders, even if it only uses one field. A common accident is value={{ user, setUser }}: that object is new on every render of the provider, so all consumers re-render whenever the provider re-renders for any reason. Wrap it in useMemo, or pass values that are already stable.

Split contexts by how often they change. The dispatch function from useReducer never changes, so put it in its own context; components that only send actions then never re-render from state changes. Context is great for values that change rarely, like theme, locale or the signed-in user. For data that updates many times per second, a store library like Zustand, or useSyncExternalStore, lets components subscribe to just the slice they need.

  • Every consumer re-renders when the value changes
  • Memoize object values with useMemo
  • Separate StateContext and DispatchContext
  • Fast-changing data: use a store with selectors

Writing a good reducer

A reducer is a pure function: (state, action) returns the next state. It must not mutate state, call APIs, read the current time or generate random ids; do those in the event handler and put the results in the action. React may call reducers twice in development to catch impurity.

Name actions after what happened, not what to set: { type: "item_added", item } reads better in logs than { type: "set_items", items }. Use a TypeScript discriminated union for actions, so each case knows its fields, and a switch with an exhaustive never check. Because reducers are plain functions, you can unit test them without rendering anything, which is one of their biggest advantages.

useState or useReducer?

useState is simpler and is the right default for independent values. useReducer starts to win when several values change together, when the next state depends on the previous one in non-trivial ways, or when many event handlers update the same state. Moving that logic into a reducer makes components shorter: handlers just dispatch.

The reducer is also easier to debug: you can log each action and the resulting state in one place. Both hooks can be mixed freely in one component, and you can switch from one to the other later without changing the component's output.

ComparePicking the state hook
useState
  • One or a few independent values
  • Simple updates like toggle or set
  • Logic sits in each handler
  • Least code
useReducer
  • Several values that change together
  • Many actions on the same data
  • All rules in one pure function
  • Easy to unit test and log

When not to reach for context

Passing a prop through two levels is fine and makes data flow obvious. Before adding context, try composition: pass the component that needs the data as children, so the middle layers never touch it.

Server data such as product lists is usually better handled by server components in Next.js or a data library like TanStack Query, which add caching and refetching that context does not have. In the Next.js App Router, context only works in client components: the provider file needs "use client", but you can still render it in a server layout and pass server components as its children.

Learn it in 4 short steps

About 1h each. Track them with a timer in your plan.

  1. 1
    Create and provide a context~1h
  2. 2
    Consume context with useContext~1h
  3. 3
    Manage complex state with useReducer~1h
  4. 4
    Combine context and reducer for app state~1h

Key points

  • Context avoids prop drilling but every consumer re-renders when the value changes.
  • Create context, wrap a subtree in its Provider, read it with useContext.
  • A reducer must be pure: same state and action always give the same result.
  • Split contexts by concern so unrelated updates do not re-render everything.

Key terms

Tap a card to flip it. 0/5 known

Examples

tsx
type Action = { type: 'add'; id: string } | { type: 'clear' };

function cartReducer(state: string[], action: Action): string[] {
  if (action.type === 'add') return [...state, action.id];
  return [];
}

const CartContext = createContext<{ items: string[]; dispatch: React.Dispatch<Action> } | null>(null);

export function CartProvider({ children }: { children: React.ReactNode }) {
  const [items, dispatch] = useReducer(cartReducer, []);
  return <CartContext.Provider value={{ items, dispatch }}>{children}</CartContext.Provider>;
}

export const useCart = () => useContext(CartContext)!;

A reducer, a provider and a hook for consumers.

A safe theme context in React 19 style

Step 1: create the context with null as default, so a missing provider is detectable. Step 2: ThemeProvider owns the state and memoizes the value so consumers re-render only when the theme really changes. Step 3: render ThemeContext directly as the provider (React 19). Step 4: useTheme throws a clear error if used outside the provider, instead of failing later with undefined.

tsx
"use client";
import { createContext, use, useMemo, useState, type ReactNode } from "react";

type Theme = "light" | "dark";
const ThemeContext = createContext<{ theme: Theme; toggle: () => void } | null>(null);

export function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>("light");
  const value = useMemo(() => ({ theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) }), [theme]);
  return <ThemeContext value={value}>{children}</ThemeContext>;
}

export function useTheme() {
  const ctx = use(ThemeContext);
  if (!ctx) throw new Error("useTheme must be used inside ThemeProvider");
  return ctx;
}

A tested todo reducer

Step 1: type the actions as a union, named after events. Step 2: handle each action with an immutable update; ids are created in the handler and passed in, keeping the reducer pure. Step 3: test it as a plain function, no rendering needed. Step 4: in the component, useReducer(todosReducer, []) and dispatch from handlers.

ts
type Todo = { id: string; text: string; done: boolean };
type Action =
  | { type: "added"; id: string; text: string }
  | { type: "toggled"; id: string }
  | { type: "removed"; id: string };

export function todosReducer(state: Todo[], action: Action): Todo[] {
  switch (action.type) {
    case "added": return [...state, { id: action.id, text: action.text, done: false }];
    case "toggled": return state.map((t) => (t.id === action.id ? { ...t, done: !t.done } : t));
    case "removed": return state.filter((t) => t.id !== action.id);
  }
}

// test: expect(todosReducer([], { type: "added", id: "1", text: "Milk" })).toHaveLength(1);

Quick reference

  • createContext(default), wrap with the provider, read with useContext or use
  • React 19: render the context itself as the provider; Context.Provider still works
  • use(Context) can be called inside conditions; useContext cannot
  • Default to null and throw in a custom hook to catch a missing provider
  • Memoize object values passed to a provider to avoid needless re-renders
  • Put dispatch in its own context; it never changes
  • Reducers are pure: no mutation, no API calls, no Date.now() or random ids
  • In Next.js App Router, providers live in a "use client" file

Common mistakes

  • Putting all app state in one context, so every change re-renders everything.
  • Mutating state inside the reducer instead of returning a new object.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A component reads ThemeContext but no provider is above it. What does it get?

Question 2

2A provider passes value={{ user, setUser }}. Why can this cause extra re-renders?

Question 3

3Which of these is allowed inside a reducer?

Question 4

4What does React 19's use(MyContext) allow that useContext does not?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Create a LocaleContext with "en" as the default value and a Greeting component that shows Hello or Bonjour depending on the context.

  2. Exercise 2medium

    Write a counter reducer that handles increment, decrement (never below 0) and reset actions, with typed actions.

  3. Exercise 3hard

    Build a CartProvider that exposes state and dispatch through two separate contexts, plus useCart and useCartDispatch hooks that throw outside the provider.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is React context a replacement for Redux?
For many apps, context plus useReducer is enough. Libraries like Redux Toolkit or Zustand add selectors, devtools and better performance for large, frequently changing state.
Does context make my app slow?
Only when a frequently changing value is read by many components. Split contexts, memoize values, or use a store with selectors for fast-changing data.
Can I use React context in Next.js server components?
No. Server components cannot read context. Put the provider in a "use client" component and wrap your layout's children with it.

Go deeper

ShareXLinkedInWhatsApp