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