Back to results for “State Management”
React › Context API

How do you create and use a custom Context in React step by step?

Intermediate

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.

Common 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?