38 lines
921 B
Plaintext
38 lines
921 B
Plaintext
== Why is this an issue?
|
|
|
|
Providing values like an object to a React `Context` will provoke additional re-renders as
|
|
React doesn't know the object is the same.
|
|
This can significantly impact performance since the whole component tree will be re-rendered each time.
|
|
Wrapping the value in a `useMemo` hook will avoid additional render passes.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,javascript]
|
|
----
|
|
function Component() {
|
|
return (
|
|
<SomeContext.Provider value={{foo: 'bar'}}> { /* value is an object expression */ }
|
|
<SomeComponent />
|
|
</SomeContext.Provider>
|
|
);
|
|
}
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,javascript]
|
|
----
|
|
function Component() {
|
|
const foo = useMemo(() => ({foo: 'bar'}), []);
|
|
return (
|
|
<SomeContext.Provider value={foo}>
|
|
<SomeComponent />
|
|
</SomeContext.Provider>
|
|
);
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
* https://reactjs.org/docs/context.html#caveats[Context Caveats] - React documentation
|