Skip to content

React - Solving Prop Drilling with Context API

Posted on:January 10, 2026 at 02:00 AM

Hello friends! đź‘‹

Have you ever found yourself in “Prop Drilling Hell”?

You know the feeling. You have a piece of data (like a user’s name) in your main App component, but you need to display it in a ProfileCard component that is nested 5 levels deep.

So you pass the prop to the Layout, then to Header, then to UserMenu, and finally to ProfileCard. The components in the middle don’t even use the data! They just act as couriers. 📦

That’s annoying and makes your code messy.

The Solution: React Context API

React Context provides a way to pass data through the component tree without having to pass props down manually at every level.

Think of it like a teleportation portal for your data. 🌀

Step 1: Create the Context

First, we need to create a context. Usually, I create a separate file for this.

// contexts/UserContext.js
import { createContext } from 'react';

// Create the context
export const UserContext = createContext(null);

Step 2: Provide the Data

Now, we need to wrap the part of our app that needs this data with a “Provider”.

// App.js
import { useState } from 'react';
import { UserContext } from './contexts/UserContext';
import Header from './Header'; // This contains the deeply nested component

const App = () => {
  const [user, setUser] = useState({ name: "Jules", role: "Engineer" });

  return (
    // We pass the value we want to share to the Provider
    <UserContext.Provider value={user}>
      <div className="app">
        <Header />
      </div>
    </UserContext.Provider>
  );
};

Step 3: Consume the Data

Now, any component inside that Provider (no matter how deep) can access the data directly!

// components/ProfileCard.js
import { useContext } from 'react';
import { UserContext } from '../contexts/UserContext';

const ProfileCard = () => {
  // Grab the value directly from the context!
  const user = useContext(UserContext);

  if (!user) return <div>Please log in</div>;

  return (
    <div className="card">
      <h2>{user.name}</h2>
      <p>{user.role}</p>
    </div>
  );
};

See? No more passing props through Header or any other intermediate components.

When to use it?

Context is great for “global” data like:

A Word of Warning ⚠️

Don’t use Context for everything. If you use it too much, it can make your components harder to reuse because they become dependent on that specific context existing.

Also, be aware of performance. If the value in the Provider changes, all components consuming that context will re-render.

Conclusion

Context API is a powerful tool to clean up your prop drilling mess. It’s built right into React, so you don’t need external libraries like Redux for simple state sharing.

Give it a try next time you find yourself passing props deeper than 2 or 3 levels!

Happy Coding! 🚀