Using the useContext Hook
The useContext hook is the modern way to consume context in React function components. It provides a clean, simple API to access context values.
Basic useContext Usage
The hook takes a context object and returns its current value:
Loading React playground...
Reading Context in Multiple Components
Multiple components can read from the same context:
Loading React playground...
Using Multiple Contexts
Components can consume multiple contexts at once:
Loading React playground...
Context Without a Provider
When there's no Provider above a component, useContext returns the default value:
Loading React playground...
Updating Context Values
Context values can include functions to update state:
Loading React playground...
Exercise: Consume a Theme Context
Loading exercise...
Exercise: Multiple Contexts
Loading exercise...
Exercise: Context with Updater
Loading exercise...
Key Takeaways
- useContext is simple - Pass context object, get value back
- Call at component top level - Like all hooks, not inside conditions or loops
- Default value matters - Used when no Provider is above the component
- Multiple contexts work together - Call useContext multiple times for different contexts
- Context can include functions - Provide both values and updater functions

