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.
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.
function Component() {
const obj = useMemo(() => ({foo: 'bar'}), []); // value is cached by useMemo
return (
<SomeContext.Provider value={obj}> { /* Compliant */ }
<SomeComponent />
</SomeContext.Provider>
);
}