🔁 useContext() in React
The useContext()
hook allows you to share state across deeply nested components — without prop drilling. It's great for theme, auth, or global app data.
📦 1. Create a Context
Use createContext()
to define your global state container.
import { createContext } from 'react';
export const ThemeContext = createContext();
🔄 2. Provide the Context
Wrap your components with the Provider
to share values.
import { ThemeContext } from './ThemeContext';
function App() {
return (
<ThemeContext.Provider value="dark">
<Home />
</ThemeContext.Provider>
);
}
📥 3. Use the Context
Access the shared value using useContext()
in any child component.
import { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function Home() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
🌐 Real-World Use Cases
- Theme switching (light/dark mode)
- Authentication status
- Language / locale settings
- Global app configuration
Contexts are best used when you need to share state across many components without passing props manually at every level.