Context
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
When to Use Context
Context is designed to share data that can be considered “global” for a tree of React components, such as the current authenticated user, theme, or preferred language.
API
React.createContext
Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider
above it in the tree.
The defaultValue argument is only used when a component does not have a matching Provider
above it in the tree.
Context.Provider
Every Context object comes with a Provider
React component that allows consuming components to subscribe to context changes.
The Provider component accepts a
value
prop to be passed to consuming components that are descendants of thisProvider
.Provider
can be connected to many consumers.Provider
can be nested to override values deeper within the tree.All consumers that are descendants of
Provider
will re-render whenever thevalue
prop changes.
Class.contextType
The contextType
property on a class can be assigned a Context
object created by React.createContext()
. Using this property lets you consume the nearest current value of that Context
type using this.context
.
Context.Consumer
Using the Context.Consumer
component lets you subscribe to a context within a function component. The function inside the component receives the current context value and returns a React node.
Context.displayName
The displayName
string property will be used by React DevTools to determine what to display for the context.
Last updated