useContext is a React Hook used to share data between components without passing props manually through every intermediate component.
useContext helps us avoid Props Drilling by sharing data directly with the components that need it.
Imagine you have 3 components:
- App (Parent)
- Profile (Child)
- User (Grandchild)
Without useContext, we need to pass data through every component using props.
With useContext, the User component can directly access the shared data.
Example using useContext:
We will create three files.
Step 1: UserContext.jsx
Create Context:
import { createContext } from 'react';
export const UserContext = createContext();
Step 2: App.jsx
Provide data to child components.
import { UserContext } from './UserContext';
import Profile from './Profile';
function App() {
const name = "Sathish"; return ( <UserContext.Provider value={name}> <Profile /> </UserContext.Provider> ); }
export default App;
Step 3: Profile.jsx
import User from './User';
function Profile() {
return ;
}
export default Profile;
Step 4: User.jsx
Access the data directly.
import { useContext } from 'react';
import { UserContext } from './UserContext';
function User() {
const name = useContext(UserContext); return <h1>Hello {name}</h1>; }
export default User;
Output:
Hello Sathish ❤️