All articles

⚛️ Props Drilling vs Context API — What's the Difference?

How do we share that data between components? 🤔

⚛️ Props Drilling vs Context API — What's the Difference?

ᅠ 📘 Engineering Notes | From Concepts to Code — Post 15 ᅠ Imagine building a React application where multiple components need access to the logged-in user's information.

How do we share that data between components? 🤔

Two common approaches are Props Drilling and the Context API.

Let's break them down! 👇 ᅠ 1️⃣ What Is Props Drilling? 📦

Props drilling happens when we pass data through multiple component levels to reach a deeply nested component.

Example:

App → Dashboard → Profile → UserInfo

Imagine UserInfo needs the user's name.

We pass the user data from App through Dashboard and Profile using props.

✅ Simple and explicit data flow ✅ Good for small component trees

⚠️ Can become difficult to maintain when many intermediate components only forward props. ᅠ 2️⃣ What Is Context API? 🌐

React Context allows components to access shared data without passing props through every intermediate level.

Example:

const UserContext = createContext(null);

function UserInfo() { const user = useContext(UserContext);

return <h3>{user.name}</h3>; }

UserInfo can read the nearest matching context value from a provider above it.

✅ Avoids unnecessary prop drilling ✅ Useful for themes and user information ✅ Simplifies sharing data across components ᅠ 3️⃣ Real-World Example 🛒

Imagine an e-commerce application.

The logged-in user's information is needed in:

👤 Profile 🛒 Shopping Cart 📊 Dashboard ⚙️ Account Settings

Instead of passing user data through many component levels, Context can make it available to components that need it. ᅠ 4️⃣ Quick Comparison ⚖️

🔹 Props Drilling • Data passes through components • Explicit data flow • Best for simple component relationships

🔹 Context API • Shares data through a provider • Avoids intermediate prop passing • Useful for widely shared data ᅠ 5️⃣ When Should We Use Each? 🎯

Use props when only a few components need the data.

Consider Context when many components at different levels need the same information.

⚠️ Context isn't always better. Frequent context value changes can cause consuming components to re-render. ᅠ 💡 My Key Takeaway

Good React architecture isn't about avoiding props completely.

It's about choosing the simplest way to share data while keeping components maintainable.

🚀 Use props when they're enough. Use Context when it solves a real problem. ᅠ 💬 Do you prefer using props or Context API for sharing data in React? ᅠ #ReactJS #ReactHooks #SoftwareEngineering #FrontendDevelopment #WebDevelopment