When building React applications, passing data from one component to another is common. Initially, props work well. But what happens when data needs to travel through multiple nested components?
This is where useContext becomes useful.
What is useContext?
useContext is a React Hook that allows components to access shared data without manually passing props through every level.
Simply put:
useContext = Share data globally inside components without prop drilling
Why do we use useContext?
Imagine this:
App
↓
Header
↓
Navbar
↓
Profile
Suppose Profile needs user data.
Without useContext:
App → Header → Navbar → Profile
You must pass props through every component.
This becomes:
- Hard to maintain
- Repetitive
- Messy in large applications
With useContext:
App
↓
Context Provider
- Profile directly accesses data
- Much cleaner.
Step 1: Create Context
Create a separate file.
import { createContext } from "react";
const UserContext = createContext();
export default UserContext;
Step 2: Provide Data
Wrap components with Provider.
import UserContext from "./UserContext";
function App() {
const user = "Jayashree";
return(
<UserContext.Provider value={user}>
<Home />
</UserContext.Provider>
);
}
Step 3: Consume Data using useContext
import { useContext } from "react";
import UserContext from "./UserContext";
function Profile(){
const user = useContext(UserContext);
return <h1>{user}</h1>;
}
Output:
Jayashree
Real World Example
Common use cases:
- Theme switching (Dark / Light)
- Authentication data
- Logged-in user details
- Language settings
- Shopping cart data
Props vs useContext
| Props | useContext |
|---|---|
| Pass data from component to component | Share data globally |
| Causes prop drilling | Avoids prop drilling |
| Good for small data sharing | Better for common shared data |
When NOT to use useContext
Avoid using useContext for:
- Frequently changing large state
- Complex state logic
- Huge applications with many updates
In such cases:
- useReducer
- State management libraries
may be better choices.
Simple Formula
Create Context -> Provide Data -> Consume using useContext
Final Thoughts
useContext makes React applications cleaner by reducing unnecessary prop passing.
Think of it like:
"Instead of sending information through every room in a building, place it in a common notice board where everyone can read it."
That is essentially what useContext does.
Top comments (0)