2nd Practical Class:
React Context
In the previous lecture, we learned how to manage local state and encapsulate logic into custom hooks. Now we’ll extend that knowledge to sharing state across multiple components using React Context.
What is Context?
React Context is a way to share data (state, config, functions) across the component tree without prop drilling.
- ✅ Avoids passing props through multiple layers
- ✅ Useful for auth state, current user data, UI settings, notifications, or scoped state
- ✅ Can wrap the whole app or just a specific portion of the tree (scoped provider)
- ⚠️ All consumers of the context will re-render when the value changes, even if they don’t use the part of the state that changed.
Creating and Using Context
Define Context
Provide Context
Consume Context
Real-World Example
We can use context for auth state:
- = login state + actions (, )
- = user profile data (id, name, role)
Instead of drilling props, provide them at the top (or in a scoped section):
Scoped Context Example
We don’t need to wrap the whole app in a provider. Sometimes it’s better to keep the state scoped to a part of the UI.
Example: local NotificationsContext for a dashboard section:
✅ This shows how context can be scoped only to a part of the UI, keeping global state smaller and more efficient.
Recap
- Context = shared state without prop drilling
- Can wrap whole app or just a scoped section
- ⚠️ All consumers re-render when context changes
- Good for: auth, current user, scoped UI state (notifications, modals, filters, etc.)
- Best practice: wrap context with Provider + custom hook for safety and clean API