In React, data is typically passed from parent to child components using props. While this approach works well for small applications, it becomes inefficient and hard to maintain when many nested components need access to the same data. This problem is known as prop drilling. The Context API and the useContext Hook are designed to solve this issue.
Prop Drilling Problem
Prop drilling occurs when data is passed through multiple components that do not actually need it, just so a deeply nested component can access it.
Example of prop drilling:
function App() {
const user = "Akbar";
return <Parent user={user} />;
}
function Parent({ user }) {
return <Child user={user} />;
}
function Child({ user }) {
return <h1>Hello, {user}</h1>;
}
Here, the Parent component does nothing with user but still has to pass it down.
Context API Overview
The Context API allows you to create a shared data store that can be accessed by any component within a provider tree, without passing props manually at every level.
Creating a context:
import { createContext } from "react";
const UserContext = createContext();
The context includes a Provider component that supplies data to all child components.
Providing Context Data
The Provider wraps part of the component tree and makes data available to all descendants.
function App() {
const user = "Akbar";
return (
<UserContext.Provider value={user}>
<Dashboard />
</UserContext.Provider>
);
}
useContext Hook
The useContext Hook allows any child component to access the context value directly.
import { useContext } from "react";
function Dashboard() {
const user = useContext(UserContext);
return <h1>Welcome, {user}</h1>;
}
This removes the need to pass props through intermediate components.
Using Context with Objects and Functions
Context can store not just simple values but also objects and functions.
Example:
const ThemeContext = createContext();
function App() {
const theme = { color: "dark" };
return (
<ThemeContext.Provider value={theme}>
<Layout />
</ThemeContext.Provider>
);
}
Real-World Scenario
In real-world applications, context is commonly used for authentication data, theme settings, language preferences, and user roles. For example, a logged-in user’s information can be accessed by navigation, profile, and settings components without repeated prop passing.
Important Notes and Best Practices
Context should be used for data that is truly global or shared across many components. Overusing context can make components harder to reuse and test. For frequently changing data, consider performance implications, as all consumers re-render when context changes.
Use context to avoid deep prop drilling, but prefer props for component-specific data.
Summary
The Context API provides a way to share data globally within a React application. The useContext Hook makes consuming context simple and readable. Together, they help eliminate prop drilling and improve code structure, making React applications more scalable and maintainable.