createContext()

The createContext() function is used to create an instance of the Context API that other components can read. It should be used in combination with the useContext hook.

Syntax

import { createContext } from 'react';

const MyContext = createContext(defaultValue);
  • The defaultValue can either be another context made from the createContext() method or a primitive data type, including null.
  • createContext() returns a context object that should be named in PascalCase.

To pass the context down further, it is necessary to wrap the component tree in a context provider. A value prop needs to be passed inside the provider.

Example

export default function App() {
const theme = 'light';
return (
<ThemeContext.Provider value={theme}>
<Container />
</ThemeContext.Provider>
);
}

Components have to use the useContext() hook to get the context information.

Note: In legacy code, there may not only be Providers but also Consumers that wrap the components. This is no longer recommended.

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn React on Codecademy