0
0
Reactframework~3 mins

Why Avoiding prop drilling in React? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how to stop passing props like a game of telephone and make your React code simpler!

The Scenario

Imagine you have a family tree of React components. You want to share a favorite recipe from the grandparent component down to the great-grandchild. You pass it through every family member in between, even if they don't care about the recipe.

The Problem

Passing props through many layers is tiring and confusing. It clutters components that don't need the data and makes your code hard to follow and fix.

The Solution

Using React's context or state management libraries lets you share data directly with the components that need it, skipping the middle layers entirely.

Before vs After
Before
function Grandparent() {
  const recipe = 'Chocolate Cake';
  return <Parent recipe={recipe} />;
}
function Parent({ recipe }) {
  return <Child recipe={recipe} />;
}
function Child({ recipe }) {
  return <GreatGrandchild recipe={recipe} />;
}
function GreatGrandchild({ recipe }) {
  return <div>{recipe}</div>;
}
After
const RecipeContext = React.createContext();
function Grandparent() {
  const recipe = 'Chocolate Cake';
  return <RecipeContext.Provider value={recipe}><GreatGrandchild /></RecipeContext.Provider>;
}
function GreatGrandchild() {
  const recipe = React.useContext(RecipeContext);
  return <div>{recipe}</div>;
}
What It Enables

You can share data easily and cleanly across many components without messy prop passing.

Real Life Example

In a shopping app, user login info or theme settings can be accessed by any component that needs it, without passing props through every screen.

Key Takeaways

Prop drilling makes code complex and hard to maintain.

Context or state libraries let you share data directly where needed.

This keeps your React components clean and focused.