| How to Refactor a Large React Component :👈 | 👉:How to Manage State Across Multiple Pages |
How to Avoid Prop Drilling |
How to Avoid Prop Drilling in React
1. Introduction
Prop drilling is a common problem in React applications. It happens when data needs to be passed from a parent component to a deeply nested child component through multiple intermediate components.
Sometimes, intermediate components do not need the data themselves. They simply pass the props to their children.
As an application grows, this can make components difficult to maintain and understand.
Prop drilling can be avoided using React Context, component composition, custom Hooks, or state management libraries such as Redux Toolkit and Zustand.
2. What Is Prop Drilling?
Consider the following component hierarchy:
Suppose the App component has user information, but only UserDetails needs it.
Without Context, we must pass the user information through every intermediate component.
Example: Prop Drilling
function App() {
const user = {
name: "John",
email: "john@example.com"
};
return <Dashboard user={user} />;
}
function Dashboard({ user }) {
return <UserSection user={user} />;
}
function UserSection({ user }) {
return <UserProfile user={user} />;
}
function UserProfile({ user }) {
return <UserDetails user={user} />;
}
function UserDetails({ user }) {
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
Here:
Appowns the user data.Dashboardreceives the user prop.UserSectionreceives and forwards it.UserProfilereceives and forwards it.UserDetailsfinally uses the data.
The intermediate components do not use the user information. They only pass it to the next component.
This is called prop drilling.
3. Problems with Prop Drilling
- Unnecessary props: Intermediate components receive data they do not need.
- Maintenance difficulty: Changing the data structure may require updating multiple components.
- Reduced readability: Component interfaces become crowded with unrelated props.
- Tight coupling: Intermediate components become dependent on data used by deeply nested components.
- Scalability issues: Passing more and more data through several levels becomes difficult to manage.
4. Solution 1: React Context API
React Context allows components to access shared values without explicitly passing props through every intermediate component.
Instead of passing user information through the entire component tree, we can provide it through a Context Provider.
Step 1: Create a Context
import { createContext } from "react";
export const UserContext = createContext(null);
Step 2: Provide the Data
import { UserContext } from "./UserContext";
function App() {
const user = {
name: "John",
email: "john@example.com"
};
return (
<UserContext.Provider value={user}>
<Dashboard />
</UserContext.Provider>
);
}
The Provider makes the user information available to components inside it.
Step 3: Consume Context in the Required Component
import { useContext } from "react";
import { UserContext } from "./UserContext";
function UserDetails() {
const user = useContext(UserContext);
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
Now the intermediate components do not need to receive or forward the user prop.
Step 4: Simplified Component Hierarchy
Important: Context removes the need to forward props through intermediate components. It does not eliminate the component hierarchy itself.
5. Create a Custom Hook for Context
In larger applications, directly calling useContext in every component can become repetitive.
We can create a custom Hook to simplify access to Context.
File: UserContext.jsx
import {
createContext,
useContext
} from "react";
const UserContext = createContext(null);
export function UserProvider({ children }) {
const user = {
name: "John",
email: "john@example.com"
};
return (
<UserContext.Provider value={user}>
{children}
</UserContext.Provider>
);
}
export function useUser() {
const context = useContext(UserContext);
if (context === null) {
throw new Error(
"useUser must be used inside UserProvider"
);
}
return context;
}
Now any component inside the provider can access user information easily.
Usage:
function UserDetails() {
const user = useUser();
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
Wrap the application or the required section:
function App() {
return (
<UserProvider>
<Dashboard />
</UserProvider>
);
}
This approach keeps Context implementation details in one place and provides a cleaner API for consuming components.
6. Solution 2: Component Composition
Not every prop-drilling problem requires Context.
Sometimes, component composition is a simpler solution.
Composition means passing a prepared component or JSX content to another component using children or another prop.
Without Composition
function App() {
const user = {
name: "John"
};
return <Dashboard user={user} />;
}
function Dashboard({ user }) {
return <UserPanel user={user} />;
}
function UserPanel({ user }) {
return <UserProfile user={user} />;
}
function UserProfile({ user }) {
return <UserDetails user={user} />;
}
With Composition
function App() {
const user = {
name: "John"
};
return (
<Dashboard
userContent={<UserDetails user={user} />}
/>
);
}
function Dashboard({ userContent }) {
return (
<div>
<h2>Dashboard</h2>
{userContent}
</div>
);
}
function UserDetails({ user }) {
return <h3>{user.name}</h3>;
}
Now Dashboard does not need to understand the user object. It simply renders the content supplied by its parent.
When to use composition:
- Intermediate components only need to position or display content.
- You want to avoid passing unrelated data through multiple levels.
- The parent already knows which content should be rendered.
- The data is needed by a small, specific part of the UI.
7. Solution 3: State Management Libraries
For larger applications, Context may not be the most suitable solution for every shared-state requirement.
State management libraries provide centralized ways to manage and access application state.
Redux Toolkit
Components can access the required state using useSelector and update it using useDispatch.
// userSlice.js
import { createSlice } from "@reduxjs/toolkit";
const userSlice = createSlice({
name: "user",
initialState: {
name: "John",
email: "john@example.com"
},
reducers: {
updateUser(state, action) {
state.name = action.payload;
}
}
});
export const { updateUser } = userSlice.actions;
export default userSlice.reducer;
Access the data from any component connected to the Redux store:
import { useSelector } from "react-redux";
function UserDetails() {
const user = useSelector(state => state.user);
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
Zustand
import { create } from "zustand";
const useUserStore = create((set) => ({
user: {
name: "John",
email: "john@example.com"
},
updateName: (name) =>
set(state => ({
user: {
...state.user,
name
}
}))
}));
Consume the required data:
function UserDetails() {
const user = useUserStore(state => state.user);
return (
<div>
<h2>{user.name}</h2>
<p>{user.email}</p>
</div>
);
}
The component can access the store without receiving user information through intermediate components.
8. Context API vs Redux Toolkit vs Zustand
| Feature | Context API | Redux Toolkit | Zustand |
|---|---|---|---|
| Built into React | Yes | No | No |
| Setup complexity | Low | Moderate | Low |
| Centralized state | Can be implemented | Yes | Yes |
| Selectors | Not built in | Yes | Yes |
| DevTools support | Limited | Strong | Available |
| Best suited for | Shared contextual values | Complex application state | Lightweight shared state |
9. When Should You Use Each Approach?
Use Props When:
- Components are closely related.
- Data only travels one or two levels.
- The parent-child relationship is clear.
- Explicit component dependencies are desirable.
Use Component Composition When:
- Intermediate components only arrange or display content.
- You want to pass JSX instead of forwarding data.
- The parent can directly create the required child content.
Use Context API When:
- Many components need the same value.
- Data is shared across a component subtree.
- You need application-wide theme, language, or authentication information.
- You want to avoid repeatedly passing the same props.
Use Redux Toolkit or Zustand When:
- Many features share and update application state.
- State transitions are becoming difficult to manage.
- You need centralized state management.
- Selectors and additional state-management capabilities are useful.
10. Important: Context Does Not Automatically Solve Performance Problems
Context is useful for avoiding prop drilling, but it should not be used for every application value.
When a Context provider's value changes, components consuming that Context are scheduled to render again.
For example:
const value = {
user,
theme
};
return (
<AppContext.Provider value={value}>
{children}
</AppContext.Provider>
);
If the provider creates a new object on every render, its value may be considered changed even when the underlying data has not changed.
For suitable cases, use useMemo to stabilize the provider value:
const value = useMemo(
() => ({
user,
theme
}),
[user, theme]
);
return (
<AppContext.Provider value={value}>
{children}
</AppContext.Provider>
);
Other useful practices include:
- Split unrelated Context values into separate contexts when appropriate.
- Keep frequently changing state local when possible.
- Avoid placing all application state into one large Context.
- Use a state management library when more suitable.
- Measure actual rendering problems before optimizing.
11. Common Mistakes to Avoid
- Using Context for everything: Local state and normal props are often sufficient.
- Creating unnecessary global state: Keep state close to the components that use it.
- Passing too many unrelated values through one Context: Organize shared state according to responsibility.
- Ignoring component composition: Sometimes passing JSX is simpler than creating a global Context.
- Using Redux for every small application: Choose tools according to application complexity.
- Not memoizing expensive provider values when needed: Unnecessary changes can cause additional Context consumer renders.
- Confusing server state with client state: API caching and synchronization may be better handled by TanStack Query or RTK Query.
12. Best Practices
- Start with normal props for simple parent-child communication.
- Use component composition when intermediate components only arrange content.
- Use Context for values shared across a component subtree.
- Use custom Hooks to simplify Context access and reuse stateful logic.
- Use Redux Toolkit or Zustand when application state becomes more complex.
- Keep local state local whenever possible.
- Avoid unnecessarily large Context providers.
- Separate server state from client-side application state.
- Choose the simplest approach that solves the actual problem.
13. Interview Questions and Answers
Q1. What is prop drilling in React?
Prop drilling is the process of passing data through multiple intermediate components to reach a deeply nested child component, even though those intermediate components do not need the data themselves.
Q2. Why is prop drilling a problem?
It increases unnecessary dependencies between components, makes code harder to maintain, and can make component interfaces unnecessarily complex.
Q3. How can you avoid prop drilling?
We can use React Context, component composition, custom Hooks, or state management libraries such as Redux Toolkit and Zustand.
Q4. What is the difference between props and Context?
Props explicitly pass data from a parent to a child. Context allows multiple components within a provider's subtree to access shared values without forwarding props through intermediate components.
Q5. Does Context replace Redux?
No. Context is primarily a mechanism for sharing values across a component tree. Redux Toolkit provides a more complete state-management approach with centralized updates, reducers, selectors, middleware, and DevTools.
Q6. Can Context cause unnecessary re-renders?
Yes. When a provider's value changes, its consumers are scheduled to render again. Splitting contexts and stabilizing provider values can help in suitable situations.
Q7. What is component composition?
Component composition means combining smaller components to build larger UI structures. It can reduce prop drilling by allowing parents to pass prepared JSX or components instead of forwarding data through intermediate components.
Q8. When should you use Zustand instead of Context?
Zustand can be useful when multiple components need to read and update shared state independently, especially when selector-based subscriptions and a centralized store are helpful.
Q9. Should all application state be global?
No. Only state that genuinely needs to be shared should be placed in a global store or Context. Component-specific state should generally remain local.
Q10. How do you avoid prop drilling in a large React application?
Use a combination of component composition, local state, Context for shared contextual values, and a suitable state management library for complex application state. Choose each approach according to the data's responsibility and usage.
14. Final Takeaway
Prop drilling is not always bad. Passing props directly between a parent and child is a normal and useful React pattern.
It becomes a problem when data travels through many components that do not need it.
Remember these principles:
- Use props for simple parent-child communication.
- Use composition when intermediate components only arrange content.
- Use Context for shared values across a component subtree.
- Use Redux Toolkit or Zustand for more complex shared application state.
- Keep state local whenever possible.
The best solution is not to eliminate props, but to choose the right way to share data based on the application's requirements.
| How to Refactor a Large React Component :👈 | 👉:How to Manage State Across Multiple Pages |
Comments and Discussion