Overview
Context provides a way to pass data through the component tree without having to pass props down manually at every level. It’s designed to share data that can be considered “global” for a tree of React components.Creating Context
UsecreateContext to create a context object. The context comes with a Provider and Consumer.
API Signature
Frompackages/react/src/ReactContext.js:14:
Using Context with Provider
The Provider component allows consuming components to subscribe to context changes.Consuming Context
With useContext Hook (Recommended)
TheuseContext hook is the modern way to consume context values.
With Context.Consumer (Legacy)
The Consumer component uses a render prop pattern:Practical Examples
Theme Context
Authentication Context
Multiple Contexts
You can use multiple contexts in a single component:Default Values
The default value is used when a component doesn’t have a matching Provider above it:Updating Context Values
Context Internal Implementation
Frompackages/react/src/ReactContext.js:18:
_currentValue and _currentValue2 fields to support multiple concurrent renderers (e.g., React DOM and React Native running simultaneously).
Best Practices
-
Create custom hooks: Wrap
useContextin custom hooks for better error handling and type safety - Split contexts: Don’t put all global state in one context. Split by domain or update frequency
-
Provide meaningful defaults: Default values should be valid states, not just
null -
Memoize context values: Use
useMemoto prevent unnecessary re-renders - Document context shape: Use TypeScript or JSDoc to document the context structure
When to Use Context
Context is ideal for:- Theme data (color, font, etc.)
- Current authenticated user
- Locale/language preferences
- UI state (modals, tooltips)
- Frequently changing data (use state management libraries)
- Data that only a few components need (use props)
- Performance-critical updates (consider alternatives)
See Also
- Hooks - Learn about
useContextand other hooks - Component API - Component lifecycle and APIs