ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

React.js Tutorial• 7 min read

useContext & Eliminating Prop Drilling

createContext, Context.Provider, and consuming global themes and auth state

React Context allows you to broadcast global data (such as active authenticated user, color theme, or language localization) to any component in the tree without "prop drilling" through intermediate layers.

The 3 Steps of React Context

1Create: const ThemeContext = React.createContext("light");.
2Provide: Wrap parent component tree in <ThemeContext.Provider value={activeTheme}>.
3Consume: Any child at any nesting depth consumes it with const theme = React.useContext(ThemeContext);.
Global Authentication Context
const AuthContext = React.createContext(null);

export function AuthProvider({ children }) {
  const [user, setUser] = React.useState({ name: "Sameera", role: "SuperAdmin" });

  const logout = () => setUser(null);

  return (
    <AuthContext.Provider value={{ user, logout }}>
      {children}
    </AuthContext.Provider>
  );
}

// Deeply nested child consuming without prop drilling:
function UserBadge() {
  const { user, logout } = React.useContext(AuthContext);
  if (!user) return <p>Please log in.</p>;
  return (
    <div>
      <span>Signed in as: {user.name} ({user.role})</span>
      <button onClick={logout}>Sign Out</button>
    </div>
  );
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

What common React architecture problem does `useContext` solve?