How do you create and use a custom Context in React step by step?
Short answer
First you create the context using createContext, then you wrap the part of your app that needs access with a Provider component and give it a value, and finally any component inside that Provider can read the value using the useContext hook.
Advertisement
AModel answer
First you create the context using createContext, then you wrap the part of your app that needs access with a Provider component and give it a value, and finally any component inside that Provider can read the value using the useContext hook.
const UserContext = React.createContext(null);
function App() {
const [user, setUser] = useState({ name: 'Alice' });
return (
<UserContext.Provider value={user}>
<Profile />
</UserContext.Provider>
);
}
function Profile() {
const user = useContext(UserContext);
return <p>Hello, {user.name}</p>;
}Real-world example
A shopping app creates a UserContext once, wraps its entire app in a Provider holding the logged in customer's details, and lets any component, like the header or the checkout page, read that same data easily.
Likely follow-ups
- Can you have more than one Context Provider active at the same time?
- What is a good default value to give createContext when no Provider exists yet?
Related topics