How to Consume Context in React: Simple Guide with Examples
In React, you consume context by using the
useContext hook inside a functional component. First, import the context object, then call useContext(MyContext) to access the context value directly.Syntax
To consume context in React, import the context object and use the useContext hook inside your component. This hook takes the context object as an argument and returns the current context value.
MyContext: The context object created byReact.createContext().useContext(MyContext): Hook to access the context value.
javascript
import React, { useContext } from 'react'; import { MyContext } from './MyContextFile'; function MyComponent() { const value = useContext(MyContext); return <div>{value}</div>; }
Example
This example shows how to create a context, provide a value, and consume it inside a child component using useContext. The child component displays the context value.
javascript
import React, { createContext, useContext } from 'react'; const ThemeContext = createContext('light'); function DisplayTheme() { const theme = useContext(ThemeContext); return <p>The current theme is <strong>{theme}</strong>.</p>; } export default function App() { return ( <ThemeContext.Provider value="dark"> <DisplayTheme /> </ThemeContext.Provider> ); }
Output
The current theme is dark.
Common Pitfalls
Common mistakes when consuming context include:
- Trying to use
useContextoutside of a component or without a matchingProvider. - Forgetting to wrap components with the context
Provider, which causes the default value to be used unexpectedly. - Using the context object incorrectly, such as calling
useContextwith something that is not a context.
javascript
import React, { useContext, createContext } from 'react'; const MyContext = createContext('default'); // Wrong: Using useContext outside a component // const value = useContext(MyContext); // ❌ This will cause an error function Component() { // Correct: useContext inside a component const value = useContext(MyContext); return <div>{value}</div>; } // Wrong: Not wrapping with Provider export default function App() { return <Component />; // Will show 'default' instead of intended value } // Right: Wrap with Provider // <MyContext.Provider value="custom"> // <Component /> // </MyContext.Provider>
Quick Reference
- Import context and useContext:
import { useContext } from 'react'; - Consume context:
const value = useContext(MyContext); - Wrap components with Provider:
<MyContext.Provider value={...}>...</MyContext.Provider> - Only use useContext inside functional components.
Key Takeaways
Use the useContext hook inside functional components to consume context values.
Always wrap components with the matching context Provider to supply the value.
Do not call useContext outside of React components or hooks.
The useContext hook returns the current context value or the default if no Provider is found.
Consuming context simplifies passing data without prop drilling.