Published Feb 25, 2023
Contribute to Docs

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.


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.


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

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.

All contributors

Looking to contribute?

Learn React on Codecademy