06 RN - Context
State
Callbacks
Context API/Redux
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.
Context API
Create context
1 |
|
Also creates Provider and Consumer.
Consumer is mainly used in class components.
1 2 |
|
Context Provider
Every Context object comes with a Provider React component that allows consuming components to subscribe to context changes
1 2 3 |
|
or
1 2 3 |
|
defaultValue from createContext is only used, when provider is not found!
useContext hook
1 |
|
Accepts a context object (the value returned from React.createContext) and returns the current context (from provider) value for that context. The current context value is determined by the value prop of the nearest
Mutating context
Include methods for updating the state in the Context object
1 2 3 4 5 |
|
Use regular state in upper/root component and provide value for update function.
1 2 3 4 5 6 7 8 9 10 |
|