createContext()
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.
Syntax
import { createContext } from 'react';
const MyContext = createContext(defaultValue);
- The
defaultValue
can either be another context made from thecreateContext()
method or a primitive data type, includingnull
. createContext()
returns a context object that should be named inPascalCase
.
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 alsoConsumers
that wrap the components. This is no longer recommended.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn React on Codecademy
- Career path
Front-End Engineer
Front-end engineers work closely with designers to make websites beautiful, functional, and fast.Includes 34 CoursesWith Professional CertificationBeginner Friendly115 hours - Free course
Learn React
In this React course, you’ll build powerful interactive applications with one of the most popular JavaScript libraries.Intermediate13 hours