At our last react meetup, Deploying React Application with Confidence, our speaker, Huad, dive deep into context API by showing you the latest tips, tricks, and the Do’s and Don’ts of context API so that you can make the most effective use out of it.
5. In a typical React application, data is passed top-down (parent to child) via props, but such usage can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are
required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.
When to Use Context Before You Use Context API React.createContext Context.Provider Class.contextType Context.Consumer Context.displayName Examples Dynamic Context Updating Context
from a Nested Component Consuming Multiple Contexts Caveats Legacy API 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. For example, in the code below we manually thread through a “theme” prop in order to style the Button component:
Etiam massa nunc, ultricies ac velit nec, dignissim ultrices turpis. Etiam vel sodales justo. Phasellus scelerisque id ante ac fermentum. Curabitur ut vulputate nisl. Vestibulum et lorem
erat. Phasellus at tempus lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Fusce rutrum blandit tortor, at congue odio suscipit eget. Nunc felis orci,
fermentum id neque sit amet, tempor volutpat eros.
Before You Use Context Context is primarily used when some data needs to be accessible by many components at different nesting levels. Apply it sparingly because it makes component
reuse more difficult. If you only want to avoid passing some props through many levels, component composition is often a simpler solution than context.
Aliquam eu dapibus sapien. Maecenas eu felis id nibh pellentesque ultrices sed at risus. Vivamus blandit, massa quis tempus convallis, arcu est vehicula sapien, vitae tristique purus
metus sed dui. Curabitur ultricies libero varius accumsan mollis. Nullam venenatis magna lobortis, ornare nisl quis, mollis ligula. Interdum et malesuada fames ac ante ipsum primis in faucibus.
Praesent quis quam et tortor commodo tincidunt.
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. This default value can be helpful for testing components in isolation
without wrapping them. Note: passing undefined as a Provider value does not cause consuming components to use defaultValue.
Proin non dictum odio. Maecenas mattis augue eu mi pulvinar blandit. Integer iaculis non lacus vitae efficitur. In commodo, nisi ut rutrum rhoncus, massa sapien tempus nulla, et
tincidunt nulla dolor a justo. Aenean euismod metus a varius bibendum. Suspendisse urna sem, auctor in cursus ac, pharetra ut elit. Praesent eget dignissim purus. Nulla eu neque pharetra, facilisis
eros a, luctus turpis. Nullam venenatis, arcu nec condimentum ullamcorper, diam ante efficitur dolor, vitae accumsan nibh purus eget massa. Sed dignissim auctor viverra. Suspendisse placerat
vehicula tortor, ut laoreet urna condimentum interdum. Proin libero diam, eleifend sed felis a, bibendum convallis nibh.
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 this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree. All
consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. The propagation from Provider to its descendant consumers (including .contextType and
useContext) is not subject to the shouldComponentUpdate method, so the consumer is updated even when an ancestor component skips an update. Changes are determined by comparing the
new and old values using the same algorithm as Object.is.
A React component that subscribes to context changes. Using this component lets you subscribe to a context within a function component. Requires a function as a child. 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().
Because context uses reference identity to determine when to re-render, there are some gotchas that could trigger unintentional renders in consumers when a provider’s parent re-
renders. For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for value:
INTRODUCTION & APIs
What’s Context?
6. “Context provides a way to pass data through the component tree
without having to pass props down manually at every level.”
- https://reactjs.org/docs/context.html
“ Another way allowing you to implicitly share data (state) between components ”
-
me
INTRODUCTION & APIs
What’s Context?
49. Thank you for listening
Credits
https://reactjs.org/docs/context.html
https://giphy.com/explore/confused-travolta
https://knowyourmeme.com/memes/feels-good
Hinweis der Redaktion
This is sharing state. Passing prop to components is fundamentally state sharing
Why do we need this context thing
What’s a problem with passing props down like this?
It becomes cumbersome, annoying, explicit and pollute to pass down multiples levels.
I’m okay with prop drilling. So what’s the problem?
It costs you some performance
In this example
Have Buttons for selecting color at root level in <MainApp/>
Color as state
Wanna render color in <Color/> way down in the tree
In order to do that, passing down thru GP/P/C/GC
When color changes
Intermediate components have to re-render
Even the color has nothing to do with them
Only Color component needs to react to the color change
Let’s see how Context will help solve this problem
Use Color as state like previous example
Call a function
With
Param: defaulValue (required in TS)
Fallb ack
When context can’t find matching provider up in the tree
Return
Context instance
In this instance, it has a Provider component as a property
Provider component requires value prop
Value == context value
So we pass a value as an object
Containing; color and setter
Wrap everything inside it like so
useContext hook
Passing your context instance
Subscribe to change of value
The ones that your just pass as a prop
And
Give you the value as a return value
This component consume the context to get the setter function
This component consume the context to get the color value
<Color /> doestnot take any prop ===> implicitly share state
That’s it intermediate components are no longer re-render
What’s gonna happen
Talk about defaultValue
Value is undefined
dont
Improvement to error message
More meaningful
Cleaner provider
Cleaner consumer
Next: more complex example to see some more tips when using context
Explain
what is it doing
Structure
next?
Explain parts
We need
Shape
Value & setter
Color
Value & setter
next?
Wrap everything inside Provider
Consume in many parts like so
next?
Render nicely?
Intermediate comps dont rerender?
Why header re-render?
next?
Provider doesn’t necessarily have to be at root level
Wrap it closest to where it needed
next?
This can be consider two different functionality
Don’t put unrelated state al together
From what we see herer, We ONLY use shape in one
And setter in another
The way we consume it
Consume whole object with value & setter
Does not need to