What is Prop Drilling?
Definition: Passing data (props) from a parent component down through several intermediate components until it reaches the child that actually needs it.
Problem: Intermediate components receive props they donβt use, cluttering the code and making debugging harder.
function Parent() {
const message = "Hello from Parent";
return <Child message={message} />;
}
function Child({ message }) {
return <Grandchild message={message} />;
}
function Grandchild({ message }) {
return <p>{message}</p>;
}
Solutions to Avoid Prop Drilling
React Context API
Provides a way to share values without passing props manually.
const UserContext = createContext();
function App() {
return (
<UserContext.Provider value="amount">
<GrandChild />
</UserContext.Provider>
);
}
function GrandChild() {
const user = useContext(UserContext);
return <p>Hello, {user}!</p>;
}
Top comments (0)