Class 33: Context API - mwilkin-401-advanced-javascript/bend-javascript-401d2 GitHub Wiki
Context: provides a way to pass or share data through the component tree without having to pass props down manually at every level.
-
When data needs to be accessible by many components at different nesting levels.
-
- Drawback: makes component reuse more difficult
-
Not limited to a single child for a component; may pass multiple children
4 members of the API:
- React.createContet : creates a context object.
- Context.Provider : allows consuming components to subscribe to context changes
- All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes.
- One provider can be connected to many consumers
- Providers can be nested – overrides values deeper in the tree
- Accepts a value prop which can be passed to descendants.
- Class.contextType : one way to consume the context of a component; used with a class component
- Can reference lifecycle methods
- Context.Consumer : subscribes to context changes within a function component.
- Requires a function as a child.
- If no Provider for the context, the value will be the default value passed in createContex().
Caveat: unintentional renders can be triggered in consumers when a provider’s parent re-renders.
- Solved by lifting into the parent’s state.