Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 132 ยท Context and Shared State

Context

Learn React context with createContext, the Context value provider and useContext. Share theme or user data without prop drilling, understand default values and re-renders, and know when not to use it.

Props are the normal way to move data down the component tree: a parent passes values to a child, the child passes them to its own child, and so on. That is explicit and easy to follow, until a value is needed ten levels down and every component in between must accept it and pass it along just to get it there. This is called prop drilling, and it makes the middle components noisy and fragile.

Context lets a component make a value available to everything below it in the tree, no matter how deep, without passing it through props. Components that want the value reach out and read it. Typical uses are the current theme, the signed-in user, the selected language, or a router location. This lesson shows the three steps, what happens at render time, what the default value is really for, and, just as important, when context is the wrong tool. It builds on props, useState and lifting state up.

The three steps

Using context always involves the same three pieces.

  1. Create a context object with createContext(defaultValue).
  2. Provide a value by rendering the context itself as a component, <ThemeContext value={...}>, around part of the tree. In React 19 the context is the provider; the older <ThemeContext.Provider> form still works but is no longer needed.
  3. Read the value in any descendant with useContext(ThemeContext).
A theme shared through context

Page and Toolbar never mention a theme. Only Badge, which cares, reads it. Click the button: App changes its state, the provider receives a new value, and every component that called useContext(ThemeContext) renders again with the new theme.

How React finds the value

useContext(SomeContext) walks up the tree from the calling component and returns the value from the closest provider of that exact context object. Providers can be nested, and the nearest one wins. That makes it easy to override a value for one part of the page.

The nearest provider wins

Each Section reads the level from above, adds one and provides the new number to its children. The headings render as h1, h2 and h3 without anyone passing a level prop. This is a useful mental model: a context value is like a variable that every descendant sees, and a provider shadows the outer one for its subtree.

The default value

createContext(defaultValue) takes a default. It is used only when a component reads the context and there is no provider above it. It is not an initial value for the provider and it is never used when a provider exists, even a provider whose value is undefined.

The default value without a provider

The first Hello sits outside every provider, so it receives the default, en. The default is handy for components that should work standalone (in a test or a style guide) without any setup.

For values that must be provided, such as the signed-in user's actions, it is common to default to null and throw a helpful error in a small wrapper hook:

JSX
const AuthContext = createContext(null);

function useAuth() {
  const auth = useContext(AuthContext);
  if (auth === null) {
    throw new Error('useAuth must be used inside an <AuthProvider>');
  }
  return auth;
}

That turns a confusing Cannot read properties of null into a clear message at the first mistake.

A realistic example: an auth context

Context becomes powerful when the value is more than a string. Here a provider owns the user state and exposes both the data and the functions that change it. The login is a pretend one, with no real server.

User and login actions in context

Three components read the same state without a single prop. AuthProvider is a normal component that takes children, which is the standard way to wrap state and context together. Later lessons on context patterns and authentication refine this design.

Context updates re-render consumers

When a provider receives a new value, React re-renders every component that reads that context, even if its parent did not re-render and even if it is wrapped in React.memo. React compares the old and new value with Object.is: if it is the same, the consumers are skipped; if it differs, they all update.

This has one consequence that surprises people. An inline object, like value={{ user, logIn, logOut }} above, is a new object on every render of the provider. Whenever AuthProvider re-renders, all consumers re-render too, even when nothing inside the object changed. Watch it happen.

Counting consumer renders

Here the value is a plain string, so the "Unrelated clicks" button re-renders Provider but not the consumer: children is the same element object created by App, and the context value did not change, so React skips it. The console confirms it, since the consumer logs only when the color changes. Now put the same state in an object literal as the value and the story changes, which is the subject of the next lesson. Wrapping the object in useMemo is the usual fix:

JSX
const value = useMemo(() => ({ user, logIn, logOut }), [user]);

When to use context

Reach for context when many components at different depths need the same value, and that value changes rarely or is naturally global:

  • Theme, color scheme, density
  • Current locale and translations
  • The signed-in user and permissions
  • A router location or a shared form's state used by deeply nested fields
  • A service object, such as a logger or API client (dependency injection)

When not to use context

Context is not a general replacement for props, and overusing it makes components harder to reuse and test, because their inputs are hidden.

  • Try props first. Passing props through two or three levels is normal and clear. It is not "drilling" until it hurts.
  • Try composition. If you pass props only to give them to a distant child, pass the child itself, as children or another prop. Children and composition shows that the intermediate components then need to know nothing.
  • Fast-changing state. Every consumer re-renders on every change, so a mouse position or a typing field in context makes large trees slow. Use local state, or a store with selectors, see external stores.
  • Server data. Cached remote data has loading, error and refetch logic better handled by a data library, see state management libraries.

A good test: if you can describe the value as "ambient", something a component asks the environment for, like the theme, context fits. If the value is the main input a component works on, make it a prop.

Common mistakes

  • Forgetting the provider. The component gets the default value, often null or a placeholder, and the bug looks like missing data. A guard hook (useAuth above) makes it loud.
  • Different context objects. Providers and consumers match by object identity. Creating a context inside a component, or importing from two copies of a file, gives a context that never matches.
  • Putting everything in one giant context. One huge value makes every consumer update for every change. Split by topic or by how often values change.
  • Mutating the value. Context values follow the same rule as state: replace them, do not mutate them, or consumers will not update.
  • Using the old syntax in new code. <Context.Provider> and <Context.Consumer> still work, but <Context value> and useContext are the current style. use(Context) also works and can be called conditionally, see the use hook.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In React 19, how do you provide a value for ThemeContext to the components below?

    In React 19 the context object can be rendered directly as the provider. The older Context.Provider form still works but is no longer necessary.
  2. 2. When is the default value passed to createContext used?

    The default applies only when there is no matching provider above the reading component. A provider with any value, even undefined, replaces it.
  3. 3. Two nested providers of the same context give different values. Which does a component deep inside the inner one receive?

    useContext returns the value from the closest provider above the component, so inner providers override outer ones for their subtree.
  4. 4. A provider renders value={{ user, logIn }} and the provider component re-renders for an unrelated reason. What happens to consumers?

    React compares context values with Object.is. A new object literal is never equal to the old one, so every consumer re-renders unless the value is memoized.
  5. 5. Which situation is the weakest fit for context?

    Every consumer re-renders on each change, so rapidly changing values make context expensive. Keep such state local or use a store with selectors.

Summary

  • Context shares a value with a whole subtree without prop drilling: create it, provide it, read it with useContext.
  • In React 19 render <MyContext value={...}> directly; the nearest provider above a component wins.
  • The default value is only used when no provider is above the reader.
  • When the provided value changes (by Object.is), every consumer re-renders; memoize object values.
  • Wrap context in a custom provider component and a guard hook so mistakes fail loudly.
  • Prefer props and composition first; use context for ambient, slowly changing data such as theme, user and locale.

Next: Context Patterns