06 RN - Context
Context vs Prop Drilling
Global/Context API vs Prop Drilling
When to Use Context
Context is designed to share data that can be considered "global" for a tree (or subtree) of React components.
Context is primarily used when some data needs to be accessible by many components at different nesting levels.
Also creates Provider and Consumer.
Consumer is mainly used in class components.
Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes
1 2 3
defaultValue from createContext is only used, when provider is not found!
All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. (same algorithm as Object.is)
1 2 3 4 5 6 7 8
- A React component that subscribes to context changes.
- The function receives the current context value and returns a React node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree.
- If there is no Provider for this context above, the value argument will be equal to the defaultValue that was passed to createContext().
Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest
Include methods for updating the state in the Context object
1 2 3 4 5