I'm starting to think React documentation warns, but the design does not offer a solution, and you must live with the side effects of their warning - that all consumers will be re-rendered.
I noticed this too - you can use React.useMemo to create a memoized value object. That way the object is only updated when one of its dependencies updates and then avoid rerendering all consumer component trees so many times.
Your example is the only way I know how to update the context from a child.
Unfortunately, making a new object each time the Provider is rendered is specifically warned about here,
reactjs.org/docs/context.html#caveats
I'm starting to think React documentation warns, but the design does not offer a solution, and you must live with the side effects of their warning - that all consumers will be re-rendered.
I noticed this too - you can use
React.useMemo
to create a memoizedvalue
object. That way the object is only updated when one of its dependencies updates and then avoid rerendering all consumer component trees so many times.