As depicted below, I have a basic react context setup.
My desire is child components consuming the context should only re-render when the context data changes, but I'm finding that's not the case.
If I update call setData2
, which is not associated with the context, a state update is triggered on Container
which subsequently triggers a recalculation and causes the consuming child to update.
The child component in question is already using React.memo
, so it would only update if its useContext
hook led it to. But the context gets updated when Container
updates, even though data1
is unchanged.
Is it possible to fix this?
const Container = () => {
const [data1, setData1] = useState(...);
const [data2, setData2] = useState(...);
return (
<MyContext.Provider value={{ data1, setData1 }}>
// child component hierarchy
</MyContext.Provider>
);
};