Lesson 5 of 11 · 13 min · Building apps
Sharing state: useReducer, context and custom hooks
What you will learn
- Manage complex state transitions with
useReducer - Share state without prop drilling using context
- Write custom hooks to reuse logic
- Use
useReffor values that should not trigger renders - Choose between local state, context and a state library
In simple words
A counter fits in useState. A shopping cart, with adding, removing, changing quantities and clearing, has many ways to change, and several parts of the page need it. A reducer gathers all those changes in one function that takes the current state and an action ("add this item") and returns the next state. Context then lets any component read it without passing props through every layer in between.
Words to know
- Reducer: a function
(state, action) => newStatethat describes every way the state can change. - Action: an object describing what happened, such as
{ type: "add", item }. - Context: a way to make a value available to a whole subtree without passing props.
- Custom hook: your own function, starting with
use, that reuses stateful logic.
useReducer
import { useReducer } from "react";
type Item = { id: number; name: string; qty: number };
type Action =
| { type: "add"; item: Omit<Item, "qty"> }
| { type: "remove"; id: number }
| { type: "setQty"; id: number; qty: number }
| { type: "clear" };
function cartReducer(state: Item[], action: Action): Item[] {
switch (action.type) {
case "add": {
const existing = state.find((i) => i.id === action.item.id);
return existing
? state.map((i) => (i.id === existing.id ? { ...i, qty: i.qty + 1 } : i))
: [...state, { ...action.item, qty: 1 }];
}
case "remove":
return state.filter((i) => i.id !== action.id);
case "setQty":
return state.map((i) => (i.id === action.id ? { ...i, qty: Math.max(1, action.qty) } : i));
case "clear":
return [];
}
}
function Cart() {
const [items, dispatch] = useReducer(cartReducer, []);
return (
<>
<button type="button" onClick={() => dispatch({ type: "add", item: { id: 1, name: "Notebook" } })}>
Add notebook
</button>
<ul>
{items.map((i) => (
<li key={i.id}>
{i.name} x {i.qty}
<button type="button" onClick={() => dispatch({ type: "remove", id: i.id })}>Remove</button>
</li>
))}
</ul>
</>
);
}
useReducer(reducer, initialState)returns the state and adispatchfunction. You describe what happened (dispatch(action)), and the reducer decides how the state changes.- A reducer must be pure (no side effects, no mutation, no random values or dates) and return a new state object.
- With a discriminated union for
Action(the TypeScript lessons),switchgives exact types for each case, and the compiler reports unhandled actions.
useState or useReducer? Use useState for independent, simple values. Use useReducer when state has several sub-values that change together, when the next state depends on complex rules, or when many handlers update the same state; it centralises the logic in one testable function (you can unit-test the reducer without React).
Context
Passing a value through many layers of components that do not use it is prop drilling. Context lets any descendant read a value directly.
import { createContext, useContext, useState, type ReactNode } from "react";
type Theme = "light" | "dark";
type ThemeContextValue = { theme: Theme; toggle: () => void };
const ThemeContext = createContext<ThemeContextValue | null>(null);
export function ThemeProvider({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState<Theme>("light");
const value = { theme, toggle: () => setTheme((t) => (t === "light" ? "dark" : "light")) };
return <ThemeContext value={value}>{children}</ThemeContext>; // React 19: no .Provider needed
}
export function useTheme() { // a custom hook with a safety check
const ctx = useContext(ThemeContext);
if (!ctx) throw new Error("useTheme must be used inside a ThemeProvider");
return ctx;
}
// anywhere below the provider
function ThemeButton() {
const { theme, toggle } = useTheme();
return <button type="button" onClick={toggle}>Theme: {theme}</button>;
}
In React 19 you can render the context itself as the provider (<ThemeContext value={...}>); in React 18 and earlier it was <ThemeContext.Provider value={...}>. Components read it with useContext(ThemeContext) (or use(ThemeContext)). Put the provider as high as needed, such as in main.tsx.
Context plus reducer is the classic way to build app-wide state without a library:
const CartStateContext = createContext<Item[]>([]);
const CartDispatchContext = createContext<React.Dispatch<Action>>(() => {});
export function CartProvider({ children }: { children: ReactNode }) {
const [items, dispatch] = useReducer(cartReducer, []);
return (
<CartStateContext value={items}>
<CartDispatchContext value={dispatch}>{children}</CartDispatchContext>
</CartStateContext>
);
}
export const useCart = () => useContext(CartStateContext);
export const useCartDispatch = () => useContext(CartDispatchContext);
Splitting state and dispatch into two contexts means components that only dispatch (an "Add" button) do not re-render when the state changes.
What context is good and bad for
- Good for: values that many components need and that change rarely: current user, theme, locale, feature flags, router and data client instances.
- Careful: every component that reads a context re-renders when its value changes. A context holding frequently changing data (mouse position, a big form's values) re-renders everything below. Keep contexts small and focused, memoise the
valueobject if the provider re-renders often (the React Compiler does this for you), and split contexts by concern. - Context is a delivery mechanism, not a state manager: the state still lives in
useStateoruseReducer. - Before reaching for context, consider composition: pass an element down as
childreninstead of the data it needs (the props lesson).
Custom hooks
A custom hook is a function whose name starts with use and that calls other hooks. It shares logic, not state: each component that calls it gets its own state.
import { useState } from "react";
function useToggle(initial = false) {
const [on, setOn] = useState(initial);
return { on, toggle: () => setOn((v) => !v), set: setOn };
}
function useLocalStorage<T>(key: string, initial: T) {
const [value, setValue] = useState<T>(() => {
try {
const stored = localStorage.getItem(key);
return stored ? (JSON.parse(stored) as T) : initial;
} catch {
return initial;
}
});
const update = (next: T | ((prev: T) => T)) => {
setValue((prev) => {
const resolved = typeof next === "function" ? (next as (p: T) => T)(prev) : next;
try { localStorage.setItem(key, JSON.stringify(resolved)); } catch { /* storage may be full or blocked */ }
return resolved;
});
};
return [value, update] as const;
}
function Settings() {
const [theme, setTheme] = useLocalStorage<"light" | "dark">("theme", "light");
const menu = useToggle();
// ...
}
Use custom hooks to extract duplicated logic (form handling, fetching, subscriptions, media queries, debouncing), to give a name to a behaviour (useOnlineStatus) and to keep components focused on markup. Follow the rules of hooks inside them. (A hook that writes to storage inside a state updater, as above, is simplified; production code usually syncs storage in an effect.)
useRef
useRef holds a mutable value that persists across renders but does not trigger a re-render when it changes:
import { useRef } from "react";
function SearchBox() {
const inputRef = useRef<HTMLInputElement>(null);
return (
<>
<input ref={inputRef} />
<button type="button" onClick={() => inputRef.current?.focus()}>Focus the input</button>
</>
);
}
Two uses: DOM access (focus, scroll, measure; attach with the ref prop) and instance variables that are not part of the rendered output (a timer id, the previous value, a flag). Do not read or write ref.current during render; do it in event handlers and effects. In React 19, ref is an ordinary prop on function components, so forwardRef is no longer required.
Choosing where state lives
| Situation | Use |
|---|---|
| One component needs it | useState in that component |
| Two nearby components need it | lift to the closest common parent |
| Many components at different depths read it, rarely changes | context |
| Complex transitions, many update paths | useReducer (alone or with context) |
| Server data (lists, details) that needs caching, refetching, loading states | a data library such as TanStack Query (next lessons) rather than hand-made state |
| Shareable position in the app (page, filters, selected tab) | the URL (router and search params) |
| Large client state with frequent updates and selectors | a library such as Zustand, Jotai or Redux Toolkit |
| Form state | local state or a form library (the forms lesson) |
| Preferences | localStorage via a hook |
Start with the simplest option and move up only when you feel the pain. Most apps need far less global state than people expect, especially once server data and the URL are treated separately.
Common mistakes
- Mutating state inside a reducer (
state.push), or putting side effects (fetches,Date.now()) in it. - Putting everything in one giant context that re-renders the whole app.
- Using context for fast-changing values.
- Reading a context outside its provider and getting
undefined(check and throw). - Reading or writing
ref.currentduring render. - Treating a custom hook as shared state (each call has its own state; share with context or a store).
- Reaching for Redux or Zustand before simpler options are exhausted.
Try it yourself
- Build a shopping cart with
useReducer(add, remove, change quantity, clear) and unit-test the reducer without React. - Provide the cart through context and show a badge count in the header and the list on another page.
- Create
ThemeContextwith auseThemehook that throws outside the provider. - Write
useToggleanduseDebouncecustom hooks and use them in two components. - Use
useRefto focus a field when a dialog opens.
Check yourself
What is a reducer?
A pure function that takes the current state and an action and returns the next state, used with useReducer to centralise state transitions.
What problem does context solve and what is its main drawback?
It avoids prop drilling by making a value available to all descendants; every consumer re-renders when the value changes, so it suits slowly changing data.
Do two components that call the same custom hook share state?
No. Each call creates its own state; custom hooks share logic, not state.
When should you use useRef instead of useState?
For values that must persist across renders but should not cause a re-render when changed, such as DOM nodes, timer ids or previous values.
Interview questions
When would you choose useReducer over useState?
When state is an object with several related fields, when updates follow complex rules or come from many handlers, or when you want the update logic in a separate, testable pure function.
How do you avoid unnecessary re-renders with context?
Keep contexts small and split by concern (separate state and dispatch), keep the value stable (memoisation or the React Compiler), put frequently changing data elsewhere, or use a store with selector-based subscriptions.
How do you manage global state in a React app?
Prefer the simplest tool: local state, lifted state, context with a reducer for app-wide settings, the URL for navigational state, a data-fetching library for server data, and a store library such as Zustand or Redux Toolkit for complex client state.
Summary
useReducercentralises complex state changes in a pure reducer driven by typed actions.- Context shares slowly changing values without prop drilling; keep it small and split by concern.
- Custom hooks reuse logic;
useRefholds non-rendering values and DOM nodes. - Choose the simplest place for state: local, lifted, context, URL, a data library or a store.
Going deeper
- React: Extracting state logic into a reducer:
useReducerstep by step. - React: Passing data deeply with context: context patterns.
- React: Reusing logic with custom hooks: rules and examples.
- React: Referencing values with refs:
useRef.
See how much of this you can explain
A free mock interview asks you new questions on React: components, state, routing and testing for Frontend Developer and scores every answer, with what to fix.