2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-06-28 13:55:47 +02:00
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.
2022-11-29 17:57:54 +01:00
[source,javascript]
----
function Component() {
return (
2023-06-28 13:55:47 +02:00
<SomeContext.Provider value={{foo: 'bar'}}> { /* Noncompliant: value is an object literal */ }
2022-11-29 17:57:54 +01:00
<SomeComponent />
</SomeContext.Provider>
);
}
----
2023-06-28 13:55:47 +02:00
To avoid additional rerenders wrap the value in a `useMemo` hook. Use the `useCallback()` hook if the value is a function.
2022-11-29 17:57:54 +01:00
[source,javascript]
----
function Component() {
2023-06-28 13:55:47 +02:00
const obj = useMemo(() => ({foo: 'bar'}), []); // value is cached by useMemo
2022-11-29 17:57:54 +01:00
return (
2023-06-28 13:55:47 +02:00
<SomeContext.Provider value={obj}> { /* Compliant */ }
2022-11-29 17:57:54 +01:00
<SomeComponent />
</SomeContext.Provider>
);
}
----
2023-05-03 11:06:20 +02:00
== Resources
2022-11-29 17:57:54 +01:00
2023-06-28 13:55:47 +02:00
=== Documentation
2023-10-19 11:46:59 +02:00
* 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]