Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 132 ยท Context and Shared State

Context Patterns

Practical React context patterns - combine context with useReducer, split state and dispatch, write provider components, stop needless re-renders, use several contexts and inject dependencies for tests.

The previous lesson covered the mechanics: create a context, provide a value, read it with useContext. Real apps need a few more habits to make that pleasant and fast. How do you keep the logic for a shared state in one place? How do you stop every consumer re-rendering when only one needs to? How do you swap a real service for a fake one in a test?

This lesson collects the patterns that experienced React developers reach for again and again. Each one is small, and together they are the complete toolkit for application-level state that does not need a library. They build on useReducer and custom hooks.

Pattern 1: context plus a reducer

A shared piece of state usually has several operations: add, remove, toggle, clear. Instead of passing a setter and writing the update logic at every call site, keep the logic in a reducer and share two things through context: the state and the dispatch function.

A shopping list with a reducer in context

Three parts cooperate. The reducer holds the rules. The provider owns the state and publishes it. Small hooks (useList, useListDispatch) hide which context is behind them, so components never import the context objects themselves. If you later swap the implementation for a library, only the provider and those hooks change.

Pattern 2: split state and dispatch

Look again at the code above: two contexts, one for the state and one for dispatch. That is deliberate. React guarantees that dispatch from useReducer (and the setter from useState) has a stable identity across renders, so the dispatch context's value never changes. A component that only dispatches, such as AddItem, subscribes to a context that never updates, so it does not re-render when the list changes.

Compare that with one combined context carrying { items, dispatch }: every change creates a new object, and AddItem would re-render on every item added, for no reason. Seeing is believing, so count renders with both layouts.

One context versus two

Click each button three times and read the console. Layout A logs "A: button rendered" at the start and again after every click, even though the button only dispatches. Layout B logs "B: button rendered" once. The label updates in both layouts; only the unnecessary work differs.

Splitting is an optimization, not a rule. For a small tree a single context is fine and simpler. Split when profiling shows that dispatch-only components re-render too often, or when state and actions change at very different rates.

Pattern 3: the provider component

Look at how ListProvider is built: a component that calls hooks, holds state, and renders children inside the context. This is the standard shape and it has a performance benefit for free.

Because the provider receives children as a prop, the elements inside it were created by the parent, not by the provider. When the provider's state changes and it re-renders, children is the same object as before, so React skips re-rendering those elements. Only the components that actually read the changed context update. That is why the earlier counter demo did not re-render Consumer on unrelated clicks.

A provider is also the right home for a value that needs setup: initial state from props, derived callbacks, or an effect that syncs with the outside world.

JSX
function ThemeProvider({ defaultTheme = 'light', children }) {
  const [theme, setTheme] = useState(defaultTheme);
  const value = useMemo(
    () => ({ theme, toggleTheme: () => setTheme((t) => (t === 'light' ? 'dark' : 'light')) }),
    [theme]
  );
  return <ThemeContext value={value}>{children}</ThemeContext>;
}

Pattern 4: avoiding unnecessary re-renders

Everything that follows from one rule: a context update re-renders every consumer of that context. To control the cost:

  1. Memoize object values with useMemo, so the provider can re-render without changing the value.
  2. Split by change frequency. Slow data (user, theme) and fast data (cursor, form text) belong in different contexts, or in local state.
  3. Split state and dispatch as shown above.
  4. Keep consumers small. If a big component reads a context for one value, move that read into a tiny child and pass only the part it needs down as a prop. Memoized children then skip when that part is unchanged.
  5. Do not put everything in context. If a value is needed by two siblings, lifting state up to their parent is cheaper than a provider.

The following demo shows rule 1. The provider re-renders on an unrelated counter, and with a memoized value the consumer stays quiet, while the unmemoized version re-renders each time.

Memoizing the context value

Press each button twice. The plain provider creates a fresh { user } object on each render, so PlainReader logs again after every click. The memoized provider reuses the same object, and MemoReader logs only once at the start.

The React Compiler (see useMemo and useCallback) memoizes values like this automatically when your code follows the rules. Until you adopt it, useMemo on provider values is a cheap and safe habit.

Pattern 5: multiple contexts and composing providers

Apps usually have several contexts: theme, auth, locale, feature flags. Keep them separate so each changes independently. Stack the providers in one component near the root, and read each through its own hook.

Several providers working together

With many providers the nesting grows tall. Group them in one AppProviders component, and keep the order meaningful: a provider that depends on another (an auth-aware API client) must be inside it.

Pattern 6: context as dependency injection

Context is not only for state. It can carry services: an API client, a logger, a clock, a feature-flag reader. Components ask for the service and never import it directly. In production you provide the real one; in tests or a style guide you provide a fake. This is dependency injection, and it is one of the cleanest uses of context, because the value never changes.

Swapping a service through context

The same Greeting component shows two different messages depending on the provider above it. The service objects are defined once outside any component, so their identity is stable and the effect, which lists api as a dependency, runs only once for each.

Testing with providers

Because context is just a component, testing a consumer means rendering it inside a provider. A tidy approach is a helper that wraps the component under test in the providers it needs, with test values:

JSX
function renderWithProviders(ui, { theme = 'light', api = fakeApi } = {}) {
  return render(
    <ThemeContext value={theme}>
      <ApiContext value={api}>{ui}</ApiContext>
    </ThemeContext>
  );
}

That snippet uses a render function from a testing library, which this editor does not include; testing React components builds a hand-made version. The pattern matters more than the library. Two habits make providers easy to test: give providers props for initial or injected values (<ListProvider initialItems={...}>), and make the guard hook throw a clear message when a provider is missing.

Choosing between the patterns

Need Pattern
Several operations on shared state Context plus reducer
Components that only trigger actions re-render too often Split state and dispatch contexts
Provider value is an object or function useMemo / useCallback the value
Slow data and fast data mixed Separate contexts, or local state for the fast part
Same component, different services in test and production Context as dependency injection
State that must be read by many components with selectors An external store, see external stores

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why do many apps put state and dispatch in two separate contexts?

    The dispatch function never changes, so a context holding only dispatch never updates. Components that read just dispatch are not re-rendered when state changes.
  2. 2. A provider renders value={{ user }} and re-renders for an unrelated reason. What is the best fix to stop consumers re-rendering?

    useMemo keeps the same object between renders while its dependencies are unchanged, so Object.is sees no change and consumers are skipped.
  3. 3. Why does a provider that renders {children} avoid re-rendering its children when its own state changes?

    When the element object is identical to the previous one, React skips re-rendering that subtree. Only components that read the changed context update.
  4. 4. What is a good use of context as dependency injection?

    A service object rarely changes, and swapping it by providing a different value is exactly what makes components testable without changing their code.
  5. 5. Which is a reasonable reason to prefer lifting state up over a new context?

    For nearby components, lifting state to the common parent is simpler and cheaper than adding a provider, a hook and a context.

Summary

  • Combine context with a reducer: the reducer holds the rules, the provider owns state, small hooks hide the context objects.
  • Split state and dispatch contexts so components that only dispatch do not re-render on state changes.
  • Write providers as components that accept children; the children are not re-rendered by the provider's own updates.
  • Memoize object values, separate fast and slow data, and keep consumers small to avoid needless renders.
  • Use several focused contexts instead of one giant one, and group their providers in one component.
  • Context can inject services (API clients, loggers) so tests can provide fakes.

Next: External Stores and useSyncExternalStore