
what is useContext() ?
useContext() is a React Hook that enables functional components to subscribe to and read context values. It provides a way to access data that is shared across the component tree without the need for "prop drilling," which involves passing props down manually through multiple levels of nested components.
useContext() is a React Hook that allows you to use global/shared data (context) in any function component — without passing props manually at every level.
Why useContext()?
In React, if you want to pass data from a parent to deeply nested child components, you'd usually have to pass props down through every level.
useContext() + Context API solves this by sharing data globally across components.
Steps to Use useContext()
1. Create a Context
import { createContext } from 'react';
const ThemeContext = createContext(); // create context
2. Provide Context Value
Wrap a part of your app with the Provider and give it a value.
function App() {
return (
<ThemeContext.Provider value="dark">
<Header />
</ThemeContext.Provider>
);
}
3. Use the Context Value
Now any child component can access that context using useContext():
import { useContext } from 'react';
function Header() {
const theme = useContext(ThemeContext); // read context value
return <h1 className={theme}>Welcome</h1>;
}
Full Working Example
import React, { createContext, useContext } from 'react';
// Step 1: Create
const UserContext = createContext();
// Step 2: Provide
function App() {
const user = { name: 'Jigar', role: 'Developer' };
return (
<UserContext.Provider value={user}>
<Profile />
</UserContext.Provider>
);
}
// Step 3: Use in any child
function Profile() {
const user = useContext(UserContext);
return <h2>Hello, {user.name} - {user.role}</h2>;
}
Summary
Feature | Description |
---|---|
createContext() | Creates a context to share data |
.Provider | Provides the context value |
useContext() | Consumes the context value in component |
Benefit | Avoids "prop drilling" in deep trees |
When to Use useContext()
- Theme switcher (light/dark mode)
- Auth or User info (logged in user data)
- Language/localization
- App-wide settings
Comments
Add new comment