Context for Shared State in React

Learn how React context providers pass typed values to consumers, when context helps avoid prop drilling, and when local state or a store fits better.

published: reading time: 7 min read author: Geek Workbench
Quick Summary

React context passes a provider value to descendants without forwarding props through every component. This guide shows a typed theme context, a guarded hook for missing providers, and how to choose between context, local state, props, or a store. Use the examples to keep shared state scoped to the components that need it, while leaving authorization and secrets on the server.

Context for Shared State in React

Introduction

React context lets a parent provide a value deep in a component tree without intermediate components forwarding it. A theme shared by a toolbar and preview is a common example.

Context carries a value; state still lives in a component. Use local state for one owner. Consider context when many descendants need a changing value and passing props becomes awkward. It does not replace props or a state store by default.

We will build a typed theme provider, read it with a guarded hook, and compare context with local state and props.

Provider, value, and consumer

A provider owns the changing state and passes a typed value to descendants. This example uses undefined as the default so a custom hook can catch a missing provider instead of quietly returning a fake theme:

import { createContext, useContext, useState, type ReactNode } from "react";

type Theme = "light" | "dark";

interface ThemeContextValue {
  theme: Theme;
  toggleTheme: () => void;
}

const ThemeContext = createContext<ThemeContextValue | undefined>(undefined);

function ThemeProvider({ children }: { children: ReactNode }) {
  const [theme, setTheme] = useState<Theme>("light");
  const toggleTheme = () => {
    setTheme((current) => (current === "light" ? "dark" : "light"));
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
}

function useTheme(): ThemeContextValue {
  const value = useContext(ThemeContext);
  if (!value) throw new Error("useTheme must be used inside ThemeProvider");
  return value;
}

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

function App() {
  return (
    <ThemeProvider>
      <ThemeToggle />
    </ThemeProvider>
  );
}

The provider owns the state, and the hook guards against rendering outside it. ThemeToggle reads the current value and calls the update callback.

Follow the provider tree

flowchart TD
    A[ThemeProvider owns theme] --> B[Header]
    A --> C[Main]
    B --> D[ThemeToggle consumer]
    C --> E[Preview consumer]

When to Use / When NOT to Use

Use context for subtree values such as theme or locale when prop passing becomes repetitive. Keep one-control values local; for two nearby components, lift state to their parent and pass props. Avoid context when it only hides a simple parent-child relationship.

For a value used by one control, keep it local:

function SearchBox() {
  const [query, setQuery] = useState("");
  return (
    <input
      value={query}
      onChange={(event) => setQuery(event.currentTarget.value)}
    />
  );
}

The theme above is different: both the header and preview read it, so their nearest shared owner can provide it through context. Context is for sharing a value down that subtree, not a place to put every piece of state.

Trade-Off Table

Approach Use it when Trade-off
Local state and props One owner or a few nearby components use the value Values must be passed through component boundaries
Context Many descendants need the same subtree value Consumers update when the provided value changes
State store State has complex transitions or many distant subscribers Adds a library or more setup and conventions

Start with state and props; add context when prop passing gets repetitive. A store may fit better when many distant subscribers or complex updates need selectors and tooling.

Production Failure Scenarios

A consumer rendered outside ThemeProvider may crash when it reads the value. A default such as "light" can hide the missing provider; the guarded hook fails clearly. Wrap the consumer in the provider or choose a fallback only when it is valid.

A provider that combines unrelated, frequently changing values can rerender consumers that only need a stable value. Split contexts by ownership, and only memoize provider values after profiling shows avoidable work.

Security and Compliance Notes

Context is not access control. Enforce permissions on the server and keep secrets out of browser state.

Common Pitfalls and Anti-Patterns

Avoid creating context inside a component, using a fake default, or combining unrelated values in one provider. Split contexts when ownership differs.

Quick Recap Checklist

  • Create context outside components with an explicit type and default.
  • Put changing state in a provider and read it with a hook.
  • Prefer props for nearby components and local state for one owner.
  • Use a store for complex updates or many distant subscribers.
  • Enforce authorization on the server.

Interview Questions

1. What does a context provider do?
It supplies a value to matching context consumers below it in the component tree. The value can include state and callbacks for updating it.
2. Why type a context default as undefined?
It represents the missing-provider case. A custom hook can detect it and report that a consumer was rendered outside its required provider.
3. When should an app use a state store instead of context?
Consider a store when state has complex updates, many distant subscribers, or needs tooling beyond passing a shared value through a subtree.
4. What does useContext return?
It reads the nearest matching provider's current value above the calling component.
  • Without a provider, it returns the context's default.
  • A default should represent a valid fallback or an explicit missing-provider case.
5. Why use a guarded custom hook for context?
It can turn a missing provider into a clear error at the consumer boundary.
  • It avoids silently using a fake default.
  • The hook can expose the context's non-optional value to components.
6. Does context own state by itself?
No. A component such as a provider owns state and passes its current value through context.
  • Context is a way to provide and read values.
  • Use a state hook or reducer to manage changing values.
7. Which consumers update when a provider value changes?
Components reading that context receive the new value.
  • Split unrelated values when their update patterns differ.
  • Profile before adding memoization or other optimization.
8. Where should the provider be placed?
Place it above all consumers that need the value and no higher than necessary.
  • This keeps its ownership boundary clear.
  • Unrelated app areas do not need to subscribe to the same context.
9. When are props simpler than context?
Props are clearer when a value only crosses one or two nearby component boundaries.
  • The dependency stays visible in component signatures.
  • Use context when repeated forwarding becomes awkward.
10. Can context protect a secret or permission?
No. Context values are part of client-side application state.
  • Do not use them as an authorization boundary.
  • Enforce access rules on the server and keep secrets off the client.

Further Reading

Conclusion

Start with props until the same changing value crosses several component layers. When you add context, keep its provider close to the consumers so ownership stays easy to follow.

Category

Related Posts

React State with useState and TypeScript

Learn how useState snapshots work, how TypeScript infers state types, and how to update objects and arrays immutably in React components.

#react #typescript #state

Sharing State and Lifting State Up in React

Learn when sibling React components need shared state, how to lift it to their nearest common owner, and why local state often beats global state.

#react #typescript #state

Accessible React UI: Semantics, Labels, and Keyboard Use

Build React interfaces with semantic controls, connected labels, visible keyboard focus, and status announcements through practical TypeScript examples.

#react #typescript #accessibility