38 lines
1.4 KiB
Plaintext

== Why is this an issue?
Whenever the `value` property of React context changes, React will rerender the context and all its child nodes and consumers. In JavaScript, things like object literals or function expressions will create a new identity every time they are evaluated. Such constructions should not be directly used as context `value` because React will always consider they have changed. This can significantly impact performance.
[source,javascript]
----
function Component() {
return (
<SomeContext.Provider value={{foo: 'bar'}}> { /* Noncompliant: value is an object literal */ }
<SomeComponent />
</SomeContext.Provider>
);
}
----
To avoid additional rerenders wrap the value in a `useMemo` hook. Use the `useCallback()` hook if the value is a function.
[source,javascript]
----
function Component() {
const obj = useMemo(() => ({foo: 'bar'}), []); // value is cached by useMemo
return (
<SomeContext.Provider value={obj}> { /* Compliant */ }
<SomeComponent />
</SomeContext.Provider>
);
}
----
== Resources
=== Documentation
* React Documentation - https://reactjs.org/docs/context.html#caveats[Context Caveats]
* React Documentation - https://react.dev/learn/passing-data-deeply-with-context[Passing Data Deeply with Context]
* React Documentation - https://react.dev/reference/react/useCallback[`useCallback` hook]
* React Documentation - https://react.dev/reference/react/useMemo[`useMemo` hook]