Discover how to stop passing props like a game of telephone and make your React code simpler!
Why Avoiding prop drilling in React? - Purpose & Use Cases
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.
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.
Using React's context or state management libraries lets you share data directly with the components that need it, skipping the middle layers entirely.
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>;
}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>;
}You can share data easily and cleanly across many components without messy prop passing.
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.
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.