How to share data between components using Context API in React?
Use React Context API to share data globally between components without prop drilling.
Question
How to share data between components using Context API in React?
Answer
The Context API allows sharing data without prop drilling through multiple levels.
import { createContext, useContext, useState } from 'react';
const UserContext = createContext();
function UserProvider({ children }) {
const [user, setUser] = useState({ name: 'Ghazi', role: 'Engineer' });
return (
<UserContext.Provider value={{ user, setUser }}>
{children}
</UserContext.Provider>
);
}
function UserProfile() {
const { user } = useContext(UserContext);
return <p>Welcome, {user.name}!</p>;
}
function App() {
return (
<UserProvider>
<UserProfile />
</UserProvider>
);
}
✅ createContext() → creates the context
✅ Provider → makes the data available
✅ useContext() → consumes the data anywhere
Real-World Example
- Theme and localization management
- Global authentication data
- Sharing app-wide settings
Quick Practice
Create a ThemeContext that toggles dark/light mode and updates all components globally.
Summary
React Context API eliminates prop drilling and simplifies global state sharing between deeply nested components.
When should I use Context instead of props?
Use Context when data needs to be accessed deeply or globally, like themes or user data.
Does Context trigger re-renders?
Yes, all consumers re-render when the context value changes.
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.