💡 Key Takeaways
🧩 useContext: Consume shared values across components without prop drilling.
🏗️ Providers: Wrap components/subtrees with <Provider> and pass value.
🔍 Consumption: useContext reads current value and auto-updates on changes.
👥 Objects & State: Context can hold objects, functions, or configs for global state.
🎯 Use Cases: Themes, auth, settings, language, and feature flags.
🧩 What is useContext
- Consumes shared values across the component tree
- Eliminates prop drilling
- Works only in functional components
- Use with
createContext()and<Provider>
import { useContext } from 'react';
🏗️ 1. Create a Context
- Use
createContext()for a global data source - Can store strings, objects, functions
- Typically in its own file (e.g.,
ThemeContext.js) - Export context and optional helper hook
import { createContext } from 'react';
const ThemeContext = createContext();
export default ThemeContext;
🪣 2. Provide Context Value
- Wrap app or subtree with
<Provider> - Pass a
valueprop to share data - Providers can be nested
- Nearest provider overrides outer values
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
🔍 3. Consume Context in Components
- Use
useContext(MyContext)in functional components - Returns current context value
- Updates automatically on provider changes
- Works at any depth in the tree
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
👥 Example with Object Value
- Context can hold complex objects
- Perfect for user profiles, settings, or configs
- Access properties directly after
useContext - Combine with custom hooks for cleaner usage
const UserContext = createContext();
<UserContext.Provider value={{ name: 'Jane', loggedIn: true }}>
<Profile />
</UserContext.Provider>
const user = useContext(UserContext);
return <p>Welcome, {user.name}</p>;
🎯 When to Use useContext
- Authentication/session data
- Theme toggling (light/dark mode)
- Language/locale switching
- App-wide configuration or feature flags
const SettingsContext = createContext();
const settings = useContext(SettingsContext);
console.log(settings.language);