🌐 Context API in React
The Context API provides a way to pass data through the component tree without having to pass props down manually at every level. It's ideal for global data like themes, user info, or language settings.
🧱 1. Create a Context
Use createContext()
to define your shared state container:
import { createContext } from 'react';
export const UserContext = createContext();
📦 2. Provide the Context
Wrap your component tree with the Provider
and pass in the value:
import { UserContext } from './UserContext';
function App() {
const user = { name: 'John', role: 'admin' };
return (
<UserContext.Provider value={user}>
<Dashboard />
</UserContext.Provider>
);
}
📥 3. Use the Context
Inside any child component, access the shared data using useContext()
:
import { useContext } from 'react';
import { UserContext } from './UserContext';
function Dashboard() {
const user = useContext(UserContext);
return <p>Welcome, {user.name}!</p>;
}
✅ 4. When to Use Context
- Theme (light/dark mode)
- Authentication status
- User preferences
- Language (i18n)
⚠️ 5. Performance Tip
Avoid frequent updates in large contexts. Frequent re-renders can slow down performance. In such cases, consider splitting contexts or using Redux/Zustand.