What is the Context API?
The Context API is a built-in React feature that allows you to share data (state, functions, or objects) across the entire component tree without having to pass props down manually through every level. This solves the common problem known as 'prop drilling'.
The Three Pillars of Context
- createContext: Defines the 'shape' of the data and provides a default value.
- Provider: A component that wraps a section of your app and 'broadcasts' the data to all its descendants.
- useContext: A hook used by any child component to 'tune in' and consume the data.
Basic Implementation
When to Use Context
Context is best suited for data that is considered 'global' or 'broadcast' to many components. Overusing it for localized state can make components harder to reuse.
| Recommended Use | Avoid If... |
|---|---|
| Theming (Light/Dark mode) | The data is only used by two adjacent components |
| User Authentication / Permissions | The data changes multiple times per second (performance) |
| Localization (Language settings) | You want to keep a component highly generic/reusable |
| Preferred UI Settings | A simple prop-pass suffices |
Performance & Memoization
Every time the value prop of a Provider changes, all components calling useContext for that specific context will re-render. To prevent unnecessary renders, always memoize the provider value if it's an object.