useContext
useContext is a React Hook used to access shared data from a Context without passing props manually through every component.
It is useful when the same data needs to be accessed by multiple components.
Examples of data that can be shared using Context include:
- User information
- Theme
- Language
- Login status
- Application settings
Why Do We Use useContext?
Normally, data is passed from a parent component to a child component using props.
For example:
App
↓
Navbar
↓
Profile
If Profile needs some data from App, we may have to pass that data through Navbar even if Navbar does not need it.
This is called prop drilling.
App
↓ props
Navbar
↓ props
Profile
useContext helps avoid this problem.
With Context, the data can be shared directly:
Context
↙ ↘
Navbar Profile
How Does useContext Work?
There are three main steps:
- Create a Context
- Provide a value using
Provider - Access the value using
useContext
Example
Suppose we want to share a username between components.
Step 1: Create Context
import { createContext } from "react";
const UserContext = createContext();
createContext() creates a Context object.
Step 2: Provide the Value
function App() {
return (
<UserContext.Provider value="Maha">
<Profile />
</UserContext.Provider>
);
}
Here:
value="Maha"
is the data we want to share.
The Profile component is placed inside the Provider, so it can access the value.
Step 3: Access the Value Using useContext
import { useContext } from "react";
function Profile() {
const user = useContext(UserContext);
return <h2>Hello {user}</h2>;
}
Here:
const user = useContext(UserContext);
gets the value provided by:
<UserContext.Provider value="Maha">
The output will be:
Hello Maha
So the data flow is:
createContext()
↓
Context Provider
↓
value="Maha"
↓
useContext()
↓
Profile Component
useContext vs Props
| Props | useContext |
|---|---|
| Data is passed from parent to child | Data can be shared through Context |
| Useful for direct parent-child communication | Useful when many components need the same data |
| Can cause prop drilling | Helps avoid prop drilling |
| Data is passed through component props | Data is accessed using useContext()
|
Conclusion
useContext makes it easier to share data across multiple React components without passing props through every level of the component tree. It is especially useful for application-wide or shared data such as themes, user information, and settings.
Top comments (0)