DEV Community

Cover image for React - Prop drilling
G Gokul
G Gokul

Posted on

React - Prop drilling

Prop drilling:

Prop drilling (also known as "threading props") is a situation in React where data is passed from a parent component down through multiple layers of nested child components until it reaches the deeply nested component that actually needs it.

Visualizing the Problem:

Imagine you have a piece of data (like a user's theme preference) at the top level of your app, and a button deep inside needs it:
n

Code Example of Prop Drilling:

import React from 'react';

function App() {
  const user = { name: "Alex" };
  // App passes 'user' to Parent
  return <Parent user={user} />;
}

function Parent({ user }) {
  // Parent doesn't use 'user', but must pass it to Child
  return <Child user={user} />;
}

function Child({ user }) {
  // Child doesn't use 'user', but must pass it to GrandChild
  return <GrandChild user={user} />;
}

function GrandChild({ user }) {
  // Finally, GrandChild uses the data
  return <h1>Welcome back, {user.name}!</h1>;
}
Enter fullscreen mode Exit fullscreen mode

Why is Prop Drilling a Problem?

While prop drilling isn't inherently a bug and works perfectly fine for small applications, it introduces several challenges as an application grows:

  1. Code Complexity & Clutter
  2. Maintenance Overhead
  3. Tight Coupling
  4. Difficult Debugging

How to Avoid Prop Drilling:

  1. React Context API
  2. Component Composition
  3. Global State Management Libraries

Top comments (0)