Global State Management with Context API
The `Context API` enables sharing state across the component tree without passing props through every level (prop drilling).
Key concepts
Context API
Enables sharing state across the component tree without passing props through every level (prop drilling).
Step by step
Steps to Use Context API:
- Create Context: Use `React.createContext()`.
- Provide Context: Wrap components with `Context.Provider`.
- Consume Context: Use `React.useContext()` to access the context value.
When to Use Context API:
- Global state shared by multiple components (e.g., user authentication, theme settings).
Limitations:
- Frequent updates to the context value can lead to performance issues. Use `useReducer` for complex state logic.
Examples
Create Context:
const UserContext = React.createContext();Provide Context:
const App = () => {
const user = { name: 'Alice', age: 25 };
return (
<UserContext.Provider value={user}>
<Profile />
</UserContext.Provider>
);
};Consume Context:
const Profile = () => {
const user = React.useContext(UserContext);
return <p>{`Name: ${user.name}, Age: ${user.age}`}</p>;
};Stuck on this one? Talk to Sumit.
Keys: F focus mode · ← → previous / next topic · Esc leave focus