When you start learning React, you will use props to pass data from one component to another. But sometimes, passing props through many levels becomes difficult. This problem is called “Props Drilling.”
To solve this problem, React gives us a special Hook called useContext.
What is useContext?
useContext is a React Hook that allows us to share data between components without passing props manually at every level.
It works together with the Context API in React.
Instead of passing data from Parent -> Child -> Grandchild -> Great-grandchild,we can directly access the data from any component using useContext.
Why Do We Need useContext?
Imagine you are building:
Dark/Light theme feature
User login system
Shopping cart
Language selection
These data are needed in many components.
If we use props for everything, the code becomes messy and hard to manage.
So, useContext makes global data sharing simple.
How useContext Works
Step 1 – Create Context
We create a context using createContext().
import { createContext } from "react";
export const UserContext = createContext();
Step 2 – Provide Context
Wrap your components inside a Provider.
import { UserContext } from "./UserContext";
function App() {
const username = "Harini";
return (
<UserContext.Provider value={username}>
<Home />
</UserContext.Provider>
);
}
Now, all components inside can access this value.
Step 3 – Use Context
Now use useContext inside any child component.
import { useContext } from "react";
import { UserContext } from "./UserContext";
function Home() {
const user = useContext(UserContext);
return <h1>Welcome {user}</h1>;
}
Output:
Welcome Harini
Top comments (0)