1. The Problem of "Prop Drilling"
In standard React, data is passed down top-to-bottom via props. When deep components (e.g. 5 levels down) need access to user credentials or theme settings, you are forced to pass props through intermediate components that don't even need the data. This anti-pattern is known as Prop Drilling.
2. The React Context API Solution
Context provides a way to pass data through the component tree without manually passing props at every level. It consists of three parts:
createContext()– Creates the context container.– Supplies the shared data to all children.useContext(Context)– Consumes the shared data anywhere inside child components.
3. Building an Authentication Context
// AuthContext.jsx
import { createContext, useContext, useState } from 'react';
const AuthContext = createContext(null);
export function AuthProvider({ children }) {
const [user, setUser] = useState({ name: "Admin", role: "SuperAdmin" });
const login = (userData) => setUser(userData);
const logout = () => setUser(null);
return (
{children}
);
}
// Custom convenience hook for consuming AuthContext
export const useAuth = () => useContext(AuthContext);
4. Consuming Context in Deep Components
// UserProfileWidget.jsx
import { useAuth } from './AuthContext';
function UserProfileWidget() {
const { user, logout } = useAuth();
if (!user) return ;
return (
Logged in as: {user.name} ({user.role})
);
}