| Avoid Stale State React Hooks :👈 | 👉:Manage Complex Forms with React Hooks |
How to Use useContext Without Prop Drilling |
How to Use useContext Without Prop Drilling in React
1. What Is Prop Drilling in React?
Prop drilling occurs when data is passed through multiple intermediate components using props, even though those components do not need the data themselves.
Consider an application with the following component hierarchy:
App
└── Dashboard
└── UserPanel
└── UserProfile
└── UserName
Suppose the App component stores the current user's name, and only UserName needs to display it.
Example: Prop Drilling
function App() {
const userName = "Alex";
return <Dashboard userName={userName} />;
}
function Dashboard({ userName }) {
return <UserPanel userName={userName} />;
}
function UserPanel({ userName }) {
return <UserProfile userName={userName} />;
}
function UserProfile({ userName }) {
return <UserName userName={userName} />;
}
function UserName({ userName }) {
return <h2>Welcome, {userName}!</h2>;
}
Problem: The Dashboard, UserPanel, and UserProfile components pass the same prop without using it for their own logic.
This can make an application harder to maintain when data must pass through many component layers.
2. What Is useContext in React?
useContext is a React Hook that allows a component to read a value from a React context without receiving that value through every intermediate component's props.
Instead of passing the user's name through every component, you can:
- Create a context.
- Provide a value using a context provider.
- Read the value from any descendant component using
useContext.
The component hierarchy can remain the same, but the intermediate components no longer need to pass the user name.
3. Step 1: Create a Context
Use createContext() to create a context object.
import { createContext } from "react";
export const UserContext = createContext(null);
Explanation:
createContext()creates a context object.UserContextrepresents the context through which a value will be shared.nullis the default value returned when a component has no matching provider above it.
The default value is a fallback. It is not automatically updated when a provider's value changes.
4. Step 2: Provide the Context Value
Wrap the components that need access to the context with its provider.
import { createContext } from "react";
export const UserContext = createContext(null);
function App() {
const user = {
name: "Alex",
role: "Developer"
};
return (
<UserContext value={user}>
<Dashboard />
</UserContext>
);
}
export default App;
Important: In React 19, you can render the context object directly as a provider using <UserContext value={user}>.
In React 18 and earlier, use <UserContext.Provider value={user}> instead:
<UserContext.Provider value={user}>
<Dashboard />
</UserContext.Provider>
The provider makes the value available to descendant components. It does not make the value available to components outside that provider's subtree.
5. Step 3: Read the Value Using useContext
A descendant component can read the context directly using the useContext() Hook.
import { useContext } from "react";
import { UserContext } from "./UserContext";
function UserName() {
const user = useContext(UserContext);
return <h2>Welcome, {user.name}!</h2>;
}
export default UserName;
The UserName component does not need to receive a user prop.
React finds the nearest matching provider above the component and returns its current value.
6. Complete Example: Removing Prop Drilling
The following example demonstrates the complete solution using context.
import { createContext, useContext } from "react";
const UserContext = createContext(null);
function App() {
const user = {
name: "Alex",
role: "Developer"
};
return (
<UserContext value={user}>
<Dashboard />
</UserContext>
);
}
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<UserPanel />
</div>
);
}
function UserPanel() {
return (
<div>
<h2>User Panel</h2>
<UserProfile />
</div>
);
}
function UserProfile() {
return (
<div>
<h3>User Profile</h3>
<UserName />
</div>
);
}
function UserName() {
const user = useContext(UserContext);
return (
<div>
<p>Name: {user.name}</p>
<p>Role: {user.role}</p>
</div>
);
}
export default App;
Output:
Dashboard
User Panel
User Profile
Name: Alex
Role: Developer
What changed?
Appprovides the user data through context.Dashboard,UserPanel, andUserProfileno longer receive or forward user props.UserNamereads the user directly throughuseContext(UserContext).
This removes unnecessary prop passing while preserving the component hierarchy.
7. Using useContext with useState
Context becomes especially useful when multiple components need to read or update shared state.
For example, several components may need access to the current user's name, and a profile component may need to update it.
import {
createContext,
useContext,
useState
} from "react";
const UserContext = createContext(null);
function App() {
const [user, setUser] = useState({
name: "Alex"
});
return (
<UserContext value={{ user, setUser }}>
<Dashboard />
</UserContext>
);
}
function Dashboard() {
return <UserProfile />;
}
function UserProfile() {
const { user, setUser } = useContext(UserContext);
function updateName() {
setUser(previousUser => ({
...previousUser,
name: "Sam"
}));
}
return (
<div>
<p>Current user: {user.name}</p>
<button onClick={updateName}>
Change Name
</button>
</div>
);
}
export default App;
How it works:
useState()stores the user information inApp.- The provider shares both
userandsetUser. UserProfilereads those values throughuseContext().- Clicking the button updates the user's name.
- React renders the affected components again with the updated context value.
Using a functional state update helps ensure the new user object is calculated from the previous state. The spread operator preserves the other properties in that object.
8. Recommended Project Structure
For a larger application, keep context creation and provider logic separate from the components that consume it.
src/
├── contexts/
│ └── UserContext.jsx
├── components/
│ ├── Dashboard.jsx
│ └── UserProfile.jsx
├── App.jsx
└── main.jsx
UserContext.jsx
import {
createContext,
useContext,
useState
} from "react";
const UserContext = createContext(null);
export function UserProvider({ children }) {
const [user, setUser] = useState({
name: "Alex",
role: "Developer"
});
return (
<UserContext value={{ user, setUser }}>
{children}
</UserContext>
);
}
export function useUser() {
const context = useContext(UserContext);
if (context === null) {
throw new Error(
"useUser must be used within a UserProvider"
);
}
return context;
}
This example uses the React 19 provider syntax. For React 18 or earlier, replace <UserContext value={...}> with <UserContext.Provider value={...}>.
App.jsx
import { UserProvider } from "./contexts/UserContext";
import Dashboard from "./components/Dashboard";
function App() {
return (
<UserProvider>
<Dashboard />
</UserProvider>
);
}
export default App;
Dashboard.jsx
import UserProfile from "./UserProfile";
function Dashboard() {
return (
<div>
<h1>Dashboard</h1>
<UserProfile />
</div>
);
}
export default Dashboard;
UserProfile.jsx
import { useUser } from "../contexts/UserContext";
function UserProfile() {
const { user, setUser } = useUser();
return (
<div>
<p>Name: {user.name}</p>
<p>Role: {user.role}</p>
<button
onClick={() =>
setUser(previousUser => ({
...previousUser,
name: "Sam"
}))
}
>
Update User
</button>
</div>
);
}
export default UserProfile;
Why create a custom Hook such as useUser?
- It makes consuming the context simpler.
- It centralizes the check for a missing provider.
- It improves readability and reduces repeated code.
- It makes the application's context API easier to maintain.
9. Common Uses of useContext
Context is particularly useful for data that many components need to access across a component subtree.
- Authentication: Current user information and sign-in status.
- Theme: Light or dark theme selection.
- Language: Selected language or localization settings.
- Application settings: Shared preferences used by several components.
- Shopping cart: Cart data shared by product lists, navigation, and checkout components.
Context is not automatically the best solution for every shared value. For data used by only a parent and one child, passing props may be simpler and clearer.
10. Example: Theme Context
A theme is a common example because many unrelated components may need to know whether the application is using a light or dark theme.
import {
createContext,
useContext,
useState
} from "react";
const ThemeContext = createContext(null);
function App() {
const [theme, setTheme] = useState("light");
function toggleTheme() {
setTheme(previousTheme =>
previousTheme === "light" ? "dark" : "light"
);
}
return (
<ThemeContext value={{ theme, toggleTheme }}>
<Header />
<MainContent />
</ThemeContext>
);
}
function Header() {
const { theme, toggleTheme } = useContext(ThemeContext);
return (
<header>
<p>Current theme: {theme}</p>
<button onClick={toggleTheme}>
Toggle Theme
</button>
</header>
);
}
function MainContent() {
const { theme } = useContext(ThemeContext);
return <p>The current theme is {theme}.</p>;
}
export default App;
Both Header and MainContent read the same theme without receiving it through props. When the theme changes, React updates consumers that depend on the changed context value.
11. Context and Re-rendering
Context removes the need to pass props through intermediate components, but it does not prevent re-renders automatically.
When a provider receives a different value according to Object.is, React updates consumers of that context. A component that reads the context may re-render when the provider value changes, even if it is wrapped in React.memo.
Example: A New Object on Every Render
<UserContext value={{ user, setUser }}>
{children}
</UserContext>
The object { user, setUser } is newly created on every render. If the provider's parent re-renders, this can cause context consumers to re-render even when the individual values have not changed.
Possible Optimization: useMemo
import { useMemo } from "react";
const contextValue = useMemo(
() => ({ user, setUser }),
[user]
);
return (
<UserContext value={contextValue}>
{children}
</UserContext>
);
This example assumes setUser is the stable setter returned by useState. The context object is recreated when user changes, but reused when the dependencies remain unchanged.
Important: Use memoization when profiling or understanding your component structure indicates that it is useful. Do not add useMemo everywhere by default.
12. Limitations of useContext
- Re-rendering: Consumers are updated when their context value changes.
- Provider placement: A consumer can only read a matching provider above it in the component tree.
- Large shared objects: If unrelated values are combined into one context, changes can update consumers that do not need every part of that object.
- State management: Context provides values; it does not itself provide reducers, asynchronous workflows, caching, or a complete state-management architecture.
- Testing: Components that require context need an appropriate provider in their test setup.
For large applications, consider splitting unrelated contexts, such as authentication, theme, and application settings, rather than putting every shared value into one context.
13. useContext vs Props
| Feature | Props | useContext |
|---|---|---|
| How data is accessed | Passed from a parent to a child. | Read from the nearest matching provider. |
| Prop drilling | May require forwarding props through intermediate components. | Can avoid forwarding shared values through intermediate components. |
| Best suited for | Explicit data flow between related components. | Values needed by many descendants. |
| Re-rendering | Depends on parent renders, prop changes, and component behavior. | Consumers can re-render when their context value changes. |
| Visibility of dependencies | Dependencies are explicit in component props. | Context dependencies are read inside the component. |
14. Common Mistakes to Avoid
- Forgetting the provider: A consumer outside the provider receives the context's default value.
- Using the wrong provider syntax: React 19 supports
<SomeContext value={...}>; React 18 and earlier require<SomeContext.Provider value={...}>. - Assuming context prevents all prop drilling: Context avoids passing shared values through intermediate components, but ordinary props are still useful for explicit component interfaces.
- Putting everything in one context: Separate unrelated shared concerns when appropriate.
- Ignoring the default value: Choose a meaningful fallback or use a custom Hook that throws a clear error when the provider is missing.
- Expecting useContext to store state automatically: Context shares a value. Use
useStateoruseReducerwhen that value needs to be managed as state. - Assuming React.memo blocks context updates: Memoization does not prevent a component from receiving an updated context value that it consumes.
- Using context for every value: Local component state and props are often better for data used by only a small part of the tree.
15. Best Practices
- Create a separate context for each logically related shared concern.
- Place each provider as close as practical to the components that need its value.
- Use a custom Hook such as
useUser()to simplify context consumption and validate provider placement. - Use
useStateoruseReducerto manage changing context values. - Use functional state updates when the next value depends on the previous value.
- Keep context values reasonably focused to avoid unnecessary consumer updates.
- Use props when they provide a clearer and simpler interface.
- Use memoization only when it offers a meaningful performance benefit.
- Test consumers both with the expected provider and, where relevant, without it.
- Remember that context is a data-sharing mechanism, not a complete replacement for every state-management library.
16. Interview Questions and Answers
Q1. What is prop drilling?
Prop drilling is the process of passing data through intermediate components that do not need the data themselves, simply to make it available to a deeper descendant.
Q2. What is useContext?
useContext is a React Hook that lets a component read the current value of a context from the nearest matching provider above it in the component tree.
Q3. What is the difference between createContext and useContext?
createContext() creates a context object. useContext() reads that context's current value inside a component.
Q4. Does useContext replace props?
No. Props remain useful for explicit parent-to-child data flow. Context is useful when many descendants need access to the same shared value.
Q5. Can useContext be used with useState?
Yes. A provider can share both a state value and its setter, allowing descendants to read and update the shared state.
Q6. What happens if a component is outside the provider?
The component receives the default value passed to createContext(), unless another matching provider exists above it.
Q7. Does useContext cause re-renders?
Consumers can re-render when the provider's value changes. Keeping context values focused and using appropriate memoization can help reduce avoidable work.
Q8. Can we use multiple contexts in one component?
Yes. A component can call useContext() multiple times to read different contexts, such as authentication, theme, and localization.
Q9. Should all application state be stored in context?
No. Local state should remain local when only one component or a small subtree needs it. Context is most useful for values shared across multiple descendants.
Q10. What is a custom context Hook?
A custom context Hook wraps useContext() and can centralize validation and provide a convenient API, such as useUser().
17. Summary
useContext helps avoid prop drilling by allowing descendant components to access shared data directly from a context provider.
The basic process is:
- Create a context using
createContext(). - Provide the value around the relevant component subtree.
- Read the value using
useContext(). - Combine context with
useStateoruseReducerif descendants need to update shared state. - Keep contexts focused and use props when they provide a simpler solution.
Key takeaway: Use props for straightforward parent-to-child communication and use context when shared values need to be accessed by multiple descendants without passing them through every intermediate component.
| Avoid Stale State React Hooks :👈 | 👉:Manage Complex Forms with React Hooks |
Comments and Discussion