Prop Drilling vs Context API
- Prop Drilling: Passing data through multiple component levels via props.
- Context API: Provides global state accessible by any component in the subtree, avoiding prop drilling.
Prop Drilling Example
function Child({ name }) {
return <h2>Child Name: {name}</h2>;
}
function Parent({ name }) {
return <Child name={name} />;
}
function App() {
const name = "Sagar";
return <Parent name={name} />;
}
✅ Data passes through each level manually.
Context API Example
import React, { createContext, useContext } from "react";
const NameContext = createContext();
function Child() {
const name = useContext(NameContext);
return <h2>Child Name: {name}</h2>;
}
function App() {
const name = "Sagar";
return (
<NameContext.Provider value={name}>
<Child />
</NameContext.Provider>
);
}
✅ Child accesses data directly without intermediate props.
Key Points
| Feature | Prop Drilling | Context API |
|---|---|---|
| Data Passing | Through props manually | Global state via context |
| Use Case | Simple hierarchy | Deeply nested components |
| Maintenance | Hard to manage for many levels | Easier to maintain |
| Flexibility | Low | High |
Conclusion
Use Context API to avoid prop drilling and simplify state management for nested or global data.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP