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 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.