DEV Community

Cover image for PROPS DRILLING
Keerthana M
Keerthana M

Posted on

PROPS DRILLING

Props drilling:

  • Props drilling occurs when you pass data from a parent component down through multiple nested components, even if intermediate components don’t use it, to reach a deeply nested child component.

  • When building React applications, we often need to pass data from one component to another.

  • When data is passed through multiple nested components, it is called Props Drilling.

1.We are passing user from:

  1. Main Component
  2. to Parent
  3. to Child
  4. to GrandChild
    Even though only GrandChild needs it, this is called Props Drilling.

  5. Why is Props Drilling a Problem?

  • Makes code messy
  • Hard to maintain
  • Unnecessary passing of props
  • Difficult in large applications

Solving Props Drilling with useContext

  • Instead of passing props through every component level, we can use React Context API to share data directly with the component that needs it.
    Step 1: Create a Context:

  • create a context inside the same file:

import React, { createContext, useContext } from "react";

const UserContext = createContext();
Enter fullscreen mode Exit fullscreen mode

Step 2: Wrap Components with Provider

  • Now wrap the components inside UserContext.Provider.
const PropsDrilling = () => {
  const user = { name: "Ram", age: 24 };

  return (
    <UserContext.Provider value={user}>
      <div>
        <h1>Main Component</h1>
        <Parent />
      </div>
    </UserContext.Provider>
  );
};
Enter fullscreen mode Exit fullscreen mode

Step 3: Remove Prop Drilling

  • Now update components so they don’t receive user as props:
function Parent() {
  return (
    <div>
      <h2>Parent Component</h2>
      <Child />
    </div>
  );
}

function Child() {
  return (
    <div>
      <h3>Child Component</h3>
      <GrandChild />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Access Data Directly in GrandChild

Now use useContext inside GrandChild:

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

  return <h4>{user.name} is in GrandChild component.</h4>;
}
Enter fullscreen mode Exit fullscreen mode

New Flow (With Context)

PropsDrilling (Provider)
        ↓
     Parent
        ↓
      Child
        ↓
   GrandChild (useContext)

Enter fullscreen mode Exit fullscreen mode

Without Context:

  • You pass user through every component.

With Context:

  • Only the component that needs user accesses it directly.

Top comments (0)