Language
日本語
English

Caution

JavaScript is disabled in your browser.
This site uses JavaScript for features such as search.
For the best experience, please enable JavaScript before browsing this site.

  1. Home
  2. React Dictionary
  3. createContext()

createContext()

Since: React 16.8(2019)

React's createContext() is a function that creates a Context object for sharing values across the entire component tree. By combining the created Context with a Provider, you can deliver data to descendant components without passing it through props.

Syntax

import { createContext } from 'react';

// Create a Context object
// The argument specifies the default value received by consumers placed outside any Provider
const MyContext = createContext(defaultValue);

// Wrap the tree with the Provider extracted from the created Context
<MyContext.Provider value={valueToShare}>
  <ChildComponent />
</MyContext.Provider>

// Read the value from a descendant component using the useContext hook
const value = useContext(MyContext);

Context Object Members

MemberOverview
ProviderA component that provides a value to descendant components. When you pass the data you want to share to the value property, all consumers inside it receive that value.
ConsumerA legacy component for reading Context values using the render prop pattern. Using useContext() is now the standard approach.
displayNameA string property that sets a display name for identifying this Context in React DevTools. Useful for debugging.

Sample Code

An example of sharing a locale (language setting) across the entire app and accessing it directly from a deeply nested component.

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

// Create a Context for sharing locale settings
// Components placed outside the Provider receive the default value 'ja'
const LocaleContext = createContext('ja');

// Set displayName to make debugging easier
LocaleContext.displayName = 'LocaleContext';

// Helper object that returns a greeting string based on locale
var messages = {
  ja: 'Hello! (Japanese)',
  en: 'Hello!',
  fr: 'Bonjour!'
};

// A deeply nested child component
// Gets the locale directly via useContext without receiving it as a prop
function Greeting() {
  var locale = useContext(LocaleContext);
  return (
    <p>{messages[locale]}</p>
  );
}

// An intermediate component
// No need to pass locale settings through props at all
function Section() {
  return (
    <div>
      {/* Greeting reads the locale setting directly via useContext */}
      <Greeting />
    </div>
  );
}

// Root component
// Wrapping with LocaleContext.Provider makes locale available to the entire tree
function App() {
  var [locale, setLocale] = useState('ja');

  // Switch to the selected language
  function handleChange(e) {
    setLocale(e.target.value);
  }

  return (
    // Passing locale to value propagates it to all consumers inside
    <LocaleContext.Provider value={locale}>
      <select value={locale} onChange={handleChange}>
        <option value="ja">Japanese</option>
        <option value="en">English</option>
        <option value="fr">Français</option>
      </select>
      {/* The locale is available even deep inside Section → Greeting */}
      <Section />
    </LocaleContext.Provider>
  );
}

export default App;

Overview

createContext() is the starting point for managing globally shared data in React. The default value passed as an argument is only used when no corresponding Provider exists in the component tree. Note that setting the Provider's value to undefined intentionally does not fall back to the default value.

When the Provider's value changes, all descendant components that reference that Context will re-render. When passing objects or arrays as value, it is recommended to memoize them with useMemo() to prevent unnecessary re-renders caused by a new reference being generated on each render.

In real-world development, a widely used pattern is to extract createContext() and the Provider into a custom component, and to wrap the useContext() call in a custom hook. This centralizes Context usage and improves code maintainability.

Related pages: Context / useContext / Custom Hooks

Common Mistakes

Default value is used when Provider is not set up

Even if you set a default value in createContext, it is only a fallback for when no Provider exists in the component tree. If you forget to add a Provider, the actual value is never used and the unintended default value is referenced instead.

ng_example.jsx
const UserContext = createContext({ name: 'Yagami Iori', team: 'Yagami Team' });

function Profile() {
  const user = useContext(UserContext);
  // NG: no Provider, so the default value is returned
  return <p>{user.name} / {user.team}</p>;
}

function App() {
  // NG: not wrapped with Provider
  return <Profile />;
}

Fixed:

ok_example.jsx
const UserContext = createContext(null);

function Profile() {
  const user = useContext(UserContext);
  return <p>{user.name} / {user.team}</p>;
}

function App() {
  // OK: wrap with Provider and supply the actual value
  return (
    <UserContext.Provider value={{ name: 'Kusanagi Kyo', team: 'Japan Team' }}>
      <Profile />
    </UserContext.Provider>
  );
}

Recreating the Context object with createContext on every render

createContext should be called only once at module level (the top level of the file). If it is called inside a component or function, a different Context object is generated on each render. The Provider and useContext will end up referencing different Contexts, and the value will not be passed correctly.

ng_example.jsx
function App() {
  // NG: a new Context is created on every render
  const UserContext = createContext(null);

  return (
    <UserContext.Provider value={{ name: 'Terry Bogard' }}>
      <Profile />
    </UserContext.Provider>
  );
}

Fixed:

ok_example.jsx
// OK: create once at module level
const UserContext = createContext(null);

function App() {
  return (
    <UserContext.Provider value={{ name: 'Terry Bogard' }}>
      <Profile />
    </UserContext.Provider>
  );
}

Not setting displayName makes DevTools hard to read

Setting displayName on a Context object created with createContext allows you to identify it by name in React DevTools. Without it, the Context is displayed with the generic label "Context," which makes debugging harder in apps that use multiple Contexts.

example.jsx
const UserContext = createContext(null);

// Setting displayName shows "UserContext" in DevTools
UserContext.displayName = 'UserContext';

const ThemeContext = createContext('light');
ThemeContext.displayName = 'ThemeContext';

If you find any errors or copyright issues, please .