useContext·续

.panel-dark { color: #fff; background: rgb(23, 32, 42); }

.button-light, .button-dark { border: 1px solid #777; padding: 5px; margin-right: 10px; margin-top: 10px; }

.button-dark { background: #222; color: #fff; }

.button-light { background: #fff; color: #222; }


#### Scaling up with context and a reducer

In larger apps, it is common to combine context with a [reducer](/reference/react/useReducer) to extract the logic related to some state out of components. In this example, all the "wiring" is hidden in the `TasksContext.js`, which contains a reducer and two separate contexts.

Read a [full walkthrough](/learn/scaling-up-with-reducer-and-context) of this example.

```js src/App.js
import AddTask from './AddTask.js';
import TaskList from './TaskList.js';
import { TasksProvider } from './TasksContext.js';

export default function TaskApp() {
  return (
    <TasksProvider>
      <h1>Day off in Kyoto</h1>
      <AddTask />
      <TaskList />
    </TasksProvider>
  );
}

```js src/TasksContext.js import { createContext, useContext, useReducer } from 'react';

const TasksContext = createContext(null);

const TasksDispatchContext = createContext(null);

export function TasksProvider({ children }) { const [tasks, dispatch] = useReducer( tasksReducer, initialTasks );

return ( <TasksContext value={tasks}> <TasksDispatchContext value={dispatch}> {children} </TasksDispatchContext> </TasksContext> ); }

export function useTasks() { return useContext(TasksContext); }

export function useTasksDispatch() { return useContext(TasksDispatchContext); }

function tasksReducer(tasks, action) { switch (action.type) { case 'added': { return [...tasks, { id: action.id, text: action.text, done: false }]; } case 'changed': { return tasks.map(t => { if (t.id === action.task.id) { return action.task; } else { return t; } }); } case 'deleted': { return tasks.filter(t => t.id !== action.id); } default: { throw Error('Unknown action: ' + action.type); } } }

const initialTasks = [ { id: 0, text: 'Philosopher’s Path', done: true }, { id: 1, text: 'Visit the temple', done: false }, { id: 2, text: 'Drink matcha', done: false } ];


```js src/AddTask.js
import { useState } from 'react';
import { useTasksDispatch } from './TasksContext.js';

export default function AddTask() {
  const [text, setText] = useState('');
  const dispatch = useTasksDispatch();
  return (
    <>
      &lt;input
        placeholder="Add task"
        value={text}
        onChange={e => setText(e.target.value)}
      />
      &lt;button onClick={() => {
        setText('');
        dispatch({
          type: 'added',
          id: nextId++,
          text: text,
        });
      }}>Add&lt;/button>
    &lt;/>
  );
}

let nextId = 3;

```js src/TaskList.js import { useState } from 'react'; import { useTasks, useTasksDispatch } from './TasksContext.js';

export default function TaskList() { const tasks = useTasks(); return ( <ul> {tasks.map(task => ( <li key={task.id}> <Task task={task} /> </li> ))} </ul> ); }

function Task({ task }) { const [isEditing, setIsEditing] = useState(false); const dispatch = useTasksDispatch(); let taskContent; if (isEditing) { taskContent = ( <> <input value={task.text} onChange={e => { dispatch({ type: 'changed', task: { ...task, text: e.target.value } }); }} /> <button onClick={() => setIsEditing(false)}> Save </button> </> ); } else { taskContent = ( <> {task.text} <button onClick={() => setIsEditing(true)}> Edit </button> </> ); } return ( <label> <input type="checkbox" checked={task.done} onChange={e => { dispatch({ type: 'changed', task: { ...task, done: e.target.checked } }); }} /> {taskContent} <button onClick={() => { dispatch({ type: 'deleted', id: task.id }); }}> Delete </button> </label> ); }


```css
button { margin: 5px; }
li { list-style-type: none; }
ul, li { margin: 0; padding: 0; }

Specifying a fallback default value

If React can't find any providers of that particular context in the parent tree, the context value returned by useContext() will be equal to the default value that you specified when you created that context:

```js [[1, 1, "ThemeContext"], [3, 1, "null"]] const ThemeContext = createContext(null);


The default value **never changes**. If you want to update context, use it with state as [described above.](#updating-data-passed-via-context)

Often, instead of `null`, there is some more meaningful value you can use as a default, for example:

```js [[1, 1, "ThemeContext"], [3, 1, "light"]]
const ThemeContext = createContext('light');

This way, if you accidentally render some component without a corresponding provider, it won't break. This also helps your components work well in a test environment without setting up a lot of providers in the tests.

In the example below, the "Toggle theme" button is always light because it's outside any theme context provider and the default context theme value is 'light'. Try editing the default theme to be 'dark'.

import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext('light');

export default function MyApp() {
  const [theme, setTheme] = useState('light');
  return (
    <>
      &lt;ThemeContext value={theme}>
        &lt;Form />
      &lt;/ThemeContext>
      &lt;Button onClick={() => {
        setTheme(theme === 'dark' ? 'light' : 'dark');
      }}>
        Toggle theme
      &lt;/Button>
    &lt;/>
  )
}

function Form({ children }) {
  return (
    &lt;Panel title="Welcome">
      &lt;Button>Sign up&lt;/Button>
      &lt;Button>Log in&lt;/Button>
    &lt;/Panel>
  );
}

function Panel({ title, children }) {
  const theme = useContext(ThemeContext);
  const className = 'panel-' + theme;
  return (
    &lt;section className={className}>
      &lt;h1>{title}&lt;/h1>
      {children}
    &lt;/section>
  )
}

function Button({ children, onClick }) {
  const theme = useContext(ThemeContext);
  const className = 'button-' + theme;
  return (
    &lt;button className={className} onClick={onClick}>
      {children}
    &lt;/button>
  );
}
.panel-light,
.panel-dark {
  border: 1px solid black;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 10px;
}
.panel-light {
  color: #222;
  background: #fff;
}

.panel-dark {
  color: #fff;
  background: rgb(23, 32, 42);
}

.button-light,
.button-dark {
  border: 1px solid #777;
  padding: 5px;
  margin-right: 10px;
  margin-top: 10px;
}

.button-dark {
  background: #222;
  color: #fff;
}

.button-light {
  background: #fff;
  color: #222;
}

Overriding context for a part of the tree

You can override the context for a part of the tree by wrapping that part in a provider with a different value.

```js {3,5} <ThemeContext value="dark"> ... <ThemeContext value="light"> <Footer /> </ThemeContext> ... </ThemeContext>


You can nest and override providers as many times as you need.

#### Overriding a theme

Here, the button *inside* the `Footer` receives a different context value (`"light"`) than the buttons outside (`"dark"`).

```js
import { createContext, useContext } from 'react';

const ThemeContext = createContext(null);

export default function MyApp() {
  return (
    &lt;ThemeContext value="dark">
      &lt;Form />
    &lt;/ThemeContext>
  )
}

function Form() {
  return (
    &lt;Panel title="Welcome">
      &lt;Button>Sign up&lt;/Button>
      &lt;Button>Log in&lt;/Button>
      &lt;ThemeContext value="light">
        &lt;Footer />
      &lt;/ThemeContext>
    &lt;/Panel>
  );
}

function Footer() {
  return (
    &lt;footer>
      &lt;Button>Settings&lt;/Button>
    &lt;/footer>
  );
}

function Panel({ title, children }) {
  const theme = useContext(ThemeContext);
  const className = 'panel-' + theme;
  return (
    &lt;section className={className}>
      {title && &lt;h1>{title}&lt;/h1>}
      {children}
    &lt;/section>
  )
}

function Button({ children }) {
  const theme = useContext(ThemeContext);
  const className = 'button-' + theme;
  return (
    &lt;button className={className}>
      {children}
    &lt;/button>
  );
}
footer {
  margin-top: 20px;
  border-top: 1px solid #aaa;
}

.panel-light,
.panel-dark {
  border: 1px solid black;
  border-radius: 4px;
  padding: 20px;
}
.panel-light {
  color: #222;
  background: #fff;
}

.panel-dark {
  color: #fff;
  background: rgb(23, 32, 42);
}

.button-light,
.button-dark {
  border: 1px solid #777;
  padding: 5px;
  margin-right: 10px;
  margin-top: 10px;
}

.button-dark {
  background: #222;
  color: #fff;
}

.button-light {
  background: #fff;
  color: #222;
}

Automatically nested headings

You can "accumulate" information when you nest context providers. In this example, the Section component keeps track of the LevelContext which specifies the depth of the section nesting. It reads the LevelContext from the parent section, and provides the LevelContext number increased by one to its children. As a result, the Heading component can automatically decide which of the <h1>, <h2>, <h3>, ..., tags to use based on how many Section components it is nested inside of.

Read a detailed walkthrough of this example.

import Heading from './Heading.js';
import Section from './Section.js';

export default function Page() {
  return (
    &lt;Section>
      &lt;Heading>Title&lt;/Heading>
      &lt;Section>
        &lt;Heading>Heading&lt;/Heading>
        &lt;Heading>Heading&lt;/Heading>
        &lt;Heading>Heading&lt;/Heading>
        &lt;Section>
          &lt;Heading>Sub-heading&lt;/Heading>
          &lt;Heading>Sub-heading&lt;/Heading>
          &lt;Heading>Sub-heading&lt;/Heading>
          &lt;Section>
            &lt;Heading>Sub-sub-heading&lt;/Heading>
            &lt;Heading>Sub-sub-heading&lt;/Heading>
            &lt;Heading>Sub-sub-heading&lt;/Heading>
          &lt;/Section>
        &lt;/Section>
      &lt;/Section>
    &lt;/Section>
  );
}

```js src/Section.js import { useContext } from 'react'; import { LevelContext } from './LevelContext.js';

export default function Section({ children }) { const level = useContext(LevelContext); return ( <section className="section"> <LevelContext value={level + 1}> {children} </LevelContext> </section> ); }


```js src/Heading.js
import { useContext } from 'react';
import { LevelContext } from './LevelContext.js';

export default function Heading({ children }) {
  const level = useContext(LevelContext);
  switch (level) {
    case 0:
      throw Error('Heading must be inside a Section!');
    case 1:
      return &lt;h1>{children}&lt;/h1>;
    case 2:
      return &lt;h2>{children}&lt;/h2>;
    case 3:
      return &lt;h3>{children}&lt;/h3>;
    case 4:
      return &lt;h4>{children}&lt;/h4>;
    case 5:
      return &lt;h5>{children}&lt;/h5>;
    case 6:
      return &lt;h6>{children}&lt;/h6>;
    default:
      throw Error('Unknown level: ' + level);
  }
}

```js src/LevelContext.js import { createContext } from 'react';

export const LevelContext = createContext(0);


```css
.section {
  padding: 10px;
  margin: 5px;
  border-radius: 5px;
  border: 1px solid #aaa;
}

Optimizing re-renders when passing objects and functions

You can pass any values via context, including objects and functions.

```js [[2, 10, "{ currentUser, login }"]] function MyApp() { const [currentUser, setCurrentUser] = useState(null);

function login(response) { storeCredentials(response.credentials); setCurrentUser(response.user); }

return ( <AuthContext value={{ currentUser, login }}> <Page /> </AuthContext> ); }


Here, the <CodeStep step={2}>context value</CodeStep> is a JavaScript object with two properties, one of which is a function. Whenever `MyApp` re-renders (for example, on a route update), this will be a *different* object pointing at a *different* function, so React will also have to re-render all components deep in the tree that call `useContext(AuthContext)`.

In smaller apps, this is not a problem. However, there is no need to re-render them if the underlying data, like `currentUser`, has not changed. To help React take advantage of that fact, you may wrap the `login` function with [`useCallback`](/reference/react/useCallback) and wrap the object creation into [`useMemo`](/reference/react/useMemo). This is a performance optimization:

```js {6,9,11,14,17}
import { useCallback, useMemo } from 'react';

function MyApp() {
  const [currentUser, setCurrentUser] = useState(null);

const login = useCallback((response) => {
    storeCredentials(response.credentials);
    setCurrentUser(response.user);
  }, []);

const contextValue = useMemo(() => ({
    currentUser,
    login
  }), [currentUser, login]);

return (
    &lt;AuthContext value={contextValue}>
      &lt;Page />
    &lt;/AuthContext>
  );
}

As a result of this change, even if MyApp needs to re-render, the components calling useContext(AuthContext) won't need to re-render unless currentUser has changed.

Read more about useMemo and useCallback.


Troubleshooting

My component doesn't see the value from my provider

There are a few common ways that this can happen:

  1. You're rendering <SomeContext> in the same component (or below) as where you're calling useContext(). Move <SomeContext> above and outside the component calling useContext().
  2. You may have forgotten to wrap your component with <SomeContext>, or you might have put it in a different part of the tree than you thought. Check whether the hierarchy is right using React DevTools.
  3. You might be running into some build issue with your tooling that causes SomeContext as seen from the providing component and SomeContext as seen by the reading component to be two different objects. This can happen if you use symlinks, for example. You can verify this by assigning them to globals like window.SomeContext1 and window.SomeContext2 and then checking whether window.SomeContext1 === window.SomeContext2 in the console. If they're not the same, fix that issue on the build tool level.

I am always getting undefined from my context although the default value is different

You might have a provider without a value in the tree:

```js {1,2} // 🚩 Doesn't work: no value prop <ThemeContext> <Button /> </ThemeContext>


If you forget to specify `value`, it's like passing `value={undefined}`.

You may have also mistakingly used a different prop name by mistake:

```js {1,2}
// 🚩 Doesn't work: prop should be called "value"
&lt;ThemeContext theme={theme}>
   &lt;Button />
&lt;/ThemeContext>

In both of these cases you should see a warning from React in the console. To fix them, call the prop value:

js {1,2} // ✅ Passing the value prop &lt;ThemeContext value={theme}> &lt;Button /> &lt;/ThemeContext>

Note that the default value from your createContext(defaultValue) call is only used if there is no matching provider above at all. If there is a <SomeContext value={undefined}> component somewhere in the parent tree, the component calling useContext(SomeContext) will receive undefined as the context value.


Sitemap

Overview of all docs pages