useContext
useContext
useContext is a React Hook that lets you read the value of a Context from within a functional component.
Syntax
const value = useContext(SomeContext);
SomeContext: The context object you previously created withcreateContext().- Returns: The current value of the context. This is determined by the
valueprop of the nearest<SomeContext.Provider>above the calling component in the tree.
How it Works
When you call useContext(MyContext), React traverses up the component tree starting from the calling component. It looks for the closest <MyContext.Provider>.
- If it finds a Provider: It returns the exact
valueprop passed to that Provider. - If it does not find a Provider: It returns the
defaultValuethat was passed tocreateContext(defaultValue)when the context was initially created.
Example
import { useContext } from 'react';
import { UserContext } from './UserContext';
function ProfileCard() {
// 1. Pass the entire Context object (not the Provider!) to the hook
const user = useContext(UserContext);
if (!user) {
return <p>Please log in.</p>;
}
return (
<div>
<img src={user.avatar} alt="Avatar" />
<h2>{user.name}</h2>
</div>
);
}
Common Pitfalls
1. Passing the wrong argument
You must pass the Context object itself to useContext, not the Provider or the Consumer.
// ❌ BAD: Passing the Provider
const value = useContext(MyContext.Provider);
// ✅ GOOD: Passing the Context object
const value = useContext(MyContext);
2. Using it outside of the Provider tree
If a component throws an error or behaves unexpectedly, ensure that the component calling useContext is actually rendered inside (as a child of) the Context Provider. A component cannot consume context from a Provider that is rendered at the same level (as a sibling) or inside a completely different branch of the application.
3. Unnecessary Re-renders
Whenever the value prop of the nearest Provider changes, React will re-render every component that calls useContext for that specific context, regardless of whether they actually use the part of the value that changed.
Interview Questions
Q: How do you consume multiple contexts in a single functional component?
A: Very easily! You just call the useContext hook multiple times sequentially:
const theme = useContext(ThemeContext);
const user = useContext(UserContext);