Popular Searches
Popular Course Categories
Popular Courses

Avoiding Prop Drilling

Avoiding Prop Drilling

Context API and State Sharing

Avoiding Prop Drilling in React

Course: React JS Training

Topic: Avoiding Prop Drilling Using Context API, Component Composition, and Effective State Management

Learning Objective: Understand prop drilling, why it can make React applications difficult to maintain, and how to avoid unnecessary prop passing using React Context, component composition, and suitable state-management techniques.

Course Links: JustAcademy React JS Training | Register for React JS Course Demo


1. Introduction to Prop Drilling

React applications are built using reusable components arranged in a component tree. Components often need data from other components, and React allows information to be passed from parent components to child components using props.

However, when a deeply nested component needs data from a distant ancestor, the data may have to pass through several intermediate components that do not use it directly. This situation is known as prop drilling.

Prop drilling is not automatically a problem. Passing props is a normal and useful React pattern. It becomes inconvenient when many intermediate components must forward props only to deliver data to a component further down the tree.

Example Scenario

Imagine an application where the App component stores the current user's information. The ProfileAvatar component needs that information, but it is nested inside several other components:

App
 └── Page
      └── Header
           └── Navigation
                └── UserMenu
                     └── ProfileAvatar

If ProfileAvatar needs the user information, every intermediate component may need to receive and forward the user prop, even if those components do not use the information themselves.

This unnecessary forwarding can make the code more difficult to read, modify, and maintain.


2. What Is Prop Drilling?

Prop drilling is the practice of passing props through multiple levels of components so that a deeply nested component can access data defined in a higher-level component.

Basic Example of Prop Drilling

function App() {
  const user = {
    name: "Rahul",
    role: "Developer"
  };

  return <Page user={user} />;
}

function Page({ user }) {
  return <Header user={user} />;
}

function Header({ user }) {
  return <Navigation user={user} />;
}

function Navigation({ user }) {
  return <UserProfile user={user} />;
}

function UserProfile({ user }) {
  return (
    <div>
      <h2>Welcome, {user.name}</h2>
      <p>Role: {user.role}</p>
    </div>
  );
}

export default App;

Explanation

  • The App component creates the user object.
  • Page receives the user object and passes it to Header.
  • Header forwards the object to Navigation.
  • Navigation forwards the object to UserProfile.
  • UserProfile finally uses the user information.

Only UserProfile needs the user information, but several intermediate components must accept and forward it. This is an example of prop drilling.


3. Why Should We Avoid Excessive Prop Drilling?

Prop drilling can make an application harder to maintain when the component hierarchy becomes deep or when many values must be forwarded.

Common Problems

  • Code repetition: The same prop is repeatedly added to component definitions and JSX elements.
  • More maintenance: Adding or renaming a prop may require changes across multiple intermediate components.
  • Unnecessary dependencies: Components receive data that they do not actually need.
  • Reduced readability: It becomes harder to understand which component genuinely uses a particular value.
  • Complex component interfaces: Intermediate components may accumulate many unrelated props.
  • Reduced flexibility: Reusing a component in a different part of the application may become more complicated if it expects unrelated data.

Important: Avoiding prop drilling does not mean avoiding props altogether. Props remain a clear and effective way to communicate between components, especially when data is needed by direct children.


4. Method One: Use React Context API

The Context API allows a parent component to make information available to descendant components without manually passing it through every intermediate component.

Context is useful when many components at different nesting levels need the same information, such as the current user, application theme, language preference, or shared configuration.

How Context Works

  1. Create a context using createContext().
  2. Provide a value to a subtree using the context provider.
  3. Read the value in the component that needs it using useContext().

Step 1: Create a Context

import { createContext } from 'react';

export const UserContext = createContext(null);

The createContext() function creates a context object. The argument null is the default value returned when no matching provider exists above the component reading the context.

Step 2: Provide the Context Value

import { UserContext } from './UserContext';

function App() {
  const user = {
    name: "Rahul",
    role: "Developer"
  };

  return (
    <UserContext value={user}>
      <Page />
    </UserContext>
  );
}

export default App;

Here, App provides the user object to the components inside the context provider. With React 19, the context object can be used directly as the provider. In React 18 and earlier, use <UserContext.Provider value={user}> instead.

Step 3: Read the Context Value

import { useContext } from 'react';
import { UserContext } from './UserContext';

function UserProfile() {
  const user = useContext(UserContext);

  if (!user) {
    return <p>No user information available.</p>;
  }

  return (
    <div>
      <h2>Welcome, {user.name}</h2>
      <p>Role: {user.role}</p>
    </div>
  );
}

export default UserProfile;

The UserProfile component reads the user object directly from Context. It no longer needs to receive a user prop from every intermediate component.

Complete Component Structure

App
 └── UserContext Provider
      └── Page
           └── Header
                └── Navigation
                     └── UserProfile
                          └── Reads UserContext directly

Result: The intermediate components do not need to receive or forward the user prop merely to make it available to UserProfile.


5. Complete Example: Avoid Prop Drilling with Context

The following example demonstrates how to share user information through Context instead of forwarding it through several components.

import { createContext, useContext } from 'react';

const UserContext = createContext(null);

function UserProfile() {
  const user = useContext(UserContext);

  if (!user) {
    return <p>User not available</p>;
  }

  return (
    <div>
      <h2>User Profile</h2>
      <p>Name: {user.name}</p>
      <p>Email: {user.email}</p>
    </div>
  );
}

function Navigation() {
  return <UserProfile />;
}

function Header() {
  return <Navigation />;
}

function Page() {
  return <Header />;
}

export default function App() {
  const user = {
    name: "Rahul",
    email: "[email protected]"
  };

  return (
    <UserContext value={user}>
      <Page />
    </UserContext>
  );
}

How This Example Works

  • UserContext is created using createContext().
  • App supplies the user object through the provider.
  • Page, Header, and Navigation render their children without forwarding the user prop.
  • UserProfile reads the shared information using useContext().
  • The code avoids repetitive user prop declarations in the intermediate components.

Version note: If you use React 18 or an earlier version, replace <UserContext value={user}> with <UserContext.Provider value={user}> and close it using </UserContext.Provider>.


6. Method Two: Use Component Composition

Component composition is another way to reduce prop drilling. Instead of passing data through several components and making each component responsible for rendering a specific descendant, a parent can pass already-created JSX through the children prop or another component prop.

This technique can simplify component relationships when intermediate components only need to arrange or display their children.

Example: Using Children

function Layout({ children }) {
  return (
    <div className="layout">
      <header>My Application</header>
      <main>{children}</main>
    </div>
  );
}

function UserProfile({ user }) {
  return <h2>Welcome, {user.name}</h2>;
}

function App() {
  const user = { name: "Rahul" };

  return (
    <Layout>
      <UserProfile user={user} />
    </Layout>
  );
}

export default App;

Explanation

  • Layout receives content through its children prop.
  • Layout does not need to know about the user object.
  • UserProfile receives the user directly from App.
  • The intermediate layout does not need to forward the user information.

Component composition is especially useful for layout components, reusable panels, dialogs, wrappers, and page containers.

Another Composition Example

function Card({ title, children }) {
  return (
    <section className="card">
      <h2>{title}</h2>
      <div>{children}</div>
    </section>
  );
}

function App() {
  return (
    <Card title="Account">
      <p>Manage your account settings here.</p>
    </Card>
  );
}

The Card component controls the layout while its parent supplies the content. This separation reduces the need for the layout component to understand or forward unrelated data.


7. Method Three: Keep State Close to Where It Is Used

Not every value needs to be shared globally. If only one component needs a piece of information, keeping that state inside the component can prevent unnecessary prop passing and dependencies.

Example: Local State

import { useState } from 'react';

function SearchBox() {
  const [query, setQuery] = useState("");

  return (
    <div>
      <input
        value={query}
        onChange={event => setQuery(event.target.value)}
        placeholder="Search products"
      />
      <p>Search text: {query}</p>
    </div>
  );
}

export default SearchBox;

The search query is managed locally because this example uses it only inside SearchBox. There is no need to move it into Context or pass it through unrelated components.

When to Keep State Local

  • A dropdown's open or closed status is used only by that dropdown.
  • A form field's temporary input value is needed only by the form.
  • A tooltip's visibility is managed by the component displaying the tooltip.
  • A small UI interaction does not need to be accessed by distant components.

If other components later need the same value, consider lifting the state to a common parent or using another appropriate sharing technique.


8. Method Four: Use a State Management Solution When Needed

In larger React applications, shared state may become complex. Several screens may need to read or update the same information, and application logic may involve many actions and dependencies.

For these situations, developers may choose a state management solution such as Redux Toolkit or another library that fits the application's requirements.

Common Options

Approach Purpose Best Suited For
Props Pass data and callbacks between related components. Direct parent-child communication and simple component trees.
Component composition Pass JSX or children to avoid forwarding unrelated props. Reusable layouts, wrappers, panels, and dialogs.
Context API Provide values to descendants without repeated prop passing. Shared themes, user information, language settings, and other subtree-wide values.
useReducer with Context Centralize complex update logic and provide state to descendants. Complex shared state within a feature or part of an application.
Redux Toolkit or another state library Organize shared state and updates using a defined architecture. Applications with substantial shared state and complex update requirements.

Best practice: Start with the simplest approach that satisfies the application's needs. A state management library should solve a real problem rather than be introduced automatically for every application.


9. Prop Drilling vs Context API

Feature Prop Drilling Context API
Data delivery Props are forwarded through intermediate components. Descendants can read a value from a matching provider.
Intermediate components May need to accept and pass on props they do not use. Do not need to forward the context value.
Data flow visibility Explicit in each component's props. The context dependency is less visible in the component's props.
Setup Usually requires no additional context setup. Requires a context and an appropriate provider.
Suitable use cases Direct communication and shallow component trees. Values needed by many descendants at different nesting levels.
Potential downside Can create repetitive prop forwarding. Can hide dependencies and be overused.

Neither approach is universally better. Props are useful when you want a component's dependencies to be explicit. Context is useful when many descendants need access to the same value.


10. Common Use Cases for Avoiding Prop Drilling

1. User Authentication

Several components may need the current user's name, profile information, or authentication status. Context can make this information available across a relevant subtree.

2. Theme Switching

Buttons, navigation bars, cards, and other components may need to know whether the application uses a light or dark theme.

3. Language Preferences

Many components may need access to the selected language or translation settings.

4. Shopping Cart

A navigation bar, product list, and cart summary may need shared cart information. The appropriate state owner can coordinate updates and distribute the data through props or Context.

5. Application Settings

Shared configuration values can be provided to the components that need them without forwarding them through every intermediate component.


11. Common Mistakes and Their Solutions

Mistake Why It Is a Problem Solution
Using Context for every prop It adds unnecessary complexity and hides dependencies. Use props for direct and simple component communication.
Creating too many contexts without a clear purpose The application's data flow becomes harder to understand. Group related values thoughtfully and create contexts around meaningful responsibilities.
Forgetting the provider A component may receive the context's default value rather than the expected value. Wrap the component in the correct provider.
Omitting the provider's value The consumer can receive undefined rather than the expected default value. Provide the intended value explicitly.
Keeping unnecessary state at the top level Unrelated components become more dependent on a common parent. Keep state close to the components that use it.
Passing props through a layout unnecessarily The layout becomes coupled to information it does not need. Consider component composition using children or another JSX prop.
Assuming Context prevents every re-render Context consumers can re-render when their consumed value changes. Keep context values focused and optimize only when measurements show a problem.

12. Best Practices for Avoiding Prop Drilling

  • Start with props because they make component dependencies explicit.
  • Identify whether intermediate components genuinely need the values they receive.
  • Use component composition when a component only needs to arrange its children.
  • Use Context when multiple descendants need the same information.
  • Keep local UI state inside the component that owns the interaction whenever practical.
  • Lift shared state to a common parent when related components need to coordinate.
  • Use a reducer or state management library when shared update logic becomes complex.
  • Separate unrelated concerns into appropriate contexts or state owners.
  • Do not assume Context automatically improves performance; measure and optimize where necessary.
  • Keep component interfaces clear and avoid passing unnecessary data.

13. Mini Project: Theme Switching Without Prop Drilling

Project Objective: Create a simple React application in which multiple nested components can read a shared theme without receiving the theme prop at every level.

Complete Code Example

import { createContext, useContext, useState } from 'react';

const ThemeContext = createContext("light");

function ThemeButton() {
  const theme = useContext(ThemeContext);

  return (
    <button className={`button-${theme}`}>
      Current Theme: {theme}
    </button>
  );
}

function Toolbar() {
  return (
    <div>
      <h2>Toolbar</h2>
      <ThemeButton />
    </div>
  );
}

export default function App() {
  const [theme, setTheme] = useState("light");

  function toggleTheme() {
    setTheme(currentTheme =>
      currentTheme === "light" ? "dark" : "light"
    );
  }

  return (
    <ThemeContext value={theme}>
      <main>
        <h1>Theme Demo</h1>
        <Toolbar />
        <button onClick={toggleTheme}>
          Toggle Theme
        </button>
      </main>
    </ThemeContext>
  );
}

React version note: This example uses the React 19 provider syntax. For React 18 or earlier, use <ThemeContext.Provider value={theme}> instead.

How the Project Works

  1. ThemeContext is created with a default value of light.
  2. App manages the current theme using useState.
  3. ThemeContext provides the current theme to its descendants.
  4. Toolbar renders ThemeButton without forwarding a theme prop.
  5. ThemeButton reads the theme directly with useContext.
  6. Clicking Toggle Theme updates the shared state and the context value.
  7. ThemeButton receives the latest theme value from Context.

Expected Result: The displayed theme changes between light and dark without passing a theme prop through Toolbar.

Practice Extension: Add a second component that reads the same context and displays a message based on the current theme.


14. Interview Questions and Answers

Q1. What is prop drilling in React?

Answer: Prop drilling is passing data through multiple levels of components so that a deeply nested component can access information from an ancestor.

Q2. Why can prop drilling be problematic?

Answer: It can create repetitive prop forwarding, make components depend on information they do not use, and increase maintenance effort.

Q3. Does prop drilling mean that using props is wrong?

Answer: No. Props are a core React feature and are useful for explicit communication between components. The concern is unnecessary forwarding through many intermediate components.

Q4. How does Context help avoid prop drilling?

Answer: Context lets a parent provide a value to descendant components, which can read it directly with useContext instead of receiving it through every intermediate component.

Q5. What is the use of createContext()?

Answer: createContext() creates a context object that can be used to provide and read a value across a component tree.

Q6. What is the purpose of useContext()?

Answer: useContext() reads the value of the nearest matching context provider above the component that calls it.

Q7. What is component composition?

Answer: Component composition means building components by combining other components or passing JSX through props such as children. It can reduce unnecessary data forwarding through layout components.

Q8. When should you use props instead of Context?

Answer: Use props when data is needed by a direct child or a small group of related components and explicit dependencies are useful.

Q9. Can Context contain changing data?

Answer: Yes. Context can provide values derived from state. When the provided value changes, components consuming that context can update.

Q10. Does Context replace useState?

Answer: No. useState manages component state, while Context provides values to descendants. They are often used together to share changing state.

Q11. What is the difference between Context and Redux Toolkit?

Answer: Context is a built-in React mechanism for providing values across a component tree. Redux Toolkit is a separate state management solution with additional patterns and tools for organizing shared state and updates.

Q12. What should you try before introducing Context?

Answer: Check whether normal props, lifting state up, or component composition can solve the problem more simply.


15. Practice Exercises

  1. Create a nested component tree with four levels and demonstrate prop drilling using a username.
  2. Refactor the same example to use Context and useContext.
  3. Build a light/dark theme switcher without forwarding theme props through intermediate components.
  4. Create a user profile page where several components can read shared user information.
  5. Build a reusable Layout component using children so it does not need to forward unrelated data props.
  6. Create a small application that uses local state for a dropdown and Context for a shared theme.
  7. Explain when prop drilling is acceptable and when Context is a better choice.

Self-Assessment Checklist

  • Can you define prop drilling?
  • Can you explain why excessive prop forwarding can be inconvenient?
  • Can you recognize unnecessary props in intermediate components?
  • Can you create a context with createContext()?
  • Can you provide and read a context value?
  • Can you use component composition to reduce prop forwarding?
  • Can you decide whether to use props, Context, or local state?
  • Can you explain why Context should be used selectively?

16. Official Learning Resources

17. Conclusion

Avoiding prop drilling helps keep React component trees easier to understand and maintain when data must reach deeply nested components. Props remain a good choice for direct communication, while component composition can remove unnecessary forwarding through layout components. When many descendants need the same value, Context can provide a cleaner alternative. For complex shared state, a reducer or dedicated state management solution may also be appropriate.

Choose the simplest solution that keeps data flow clear, component dependencies understandable, and the application maintainable.

Explore the course: JustAcademy React JS Training | Register for React JS Course Demo

Previous Next
whatsapp