Replacing Context.Consumer with useContext
What you'll learn: How the modern useContext hook eliminates the verbosity and nesting of the old Context.Consumer render-prop pattern.
The Old Way: Context.Consumer
Before hooks, consuming context required wrapping your component's JSX in a Context.Consumer component and using a render prop pattern:
function UserProfile() {
return (
<UserContext.Consumer>
{(user) => (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
)}
</UserContext.Consumer>
);
}
This works, but quickly becomes unwieldy when you need multiple contexts or mix them with other render props.
The Modern Way: useContext Hook
With useContext, you simply call the hook at the top of your component and get the value directly:
function UserProfile() {
const user = useContext(UserContext);
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
</div>
);
}
Why Hooks Are Cleaner
Analogy: The old Consumer pattern is like needing to fill out a form inside another form to request information. The useContext hook is like walking up to a desk and simply asking for what you need.
Benefits of useContext:
- Less nesting: No wrapper components cluttering your JSX
- Multiple contexts are cleaner: Just call
useContextmultiple times instead of nesting Consumers - Works naturally with other hooks: Fits the same mental model as
useStateanduseEffect - Better readability: Your component logic stays at the top, not buried in render functions
Key Takeaway: useContext replaced the cumbersome Context.Consumer render-prop pattern with a simple hook call, making context consumption cleaner and more composable with other React features.