I have the following structure in my React code:
const Parent: React.FC<ParentProps> = (props) => {
const [value1, setValue1] = useState<any>(null);
return (
<div>
<SomeContextProvider
contextElem1={value1}
contextElem2={value2}
>
...some code here
<Child
prop1={value3}
prop2={value4}
/>
</SomeContextProvider>
</div>
);
}
export default Parent;
const Child: React.FC<ChildProps> = ({ prop1, prop2 }) => {
return (
<div>
{prop1} {prop2}
</div>
);
}
const propsAreEqual = (prevProps: ChildProps, nextProps: ChildProps) => {
return true;
}
export default React.memo(Child, propsAreEqual);
As you notice:
Child
component does not consume SomeContextChild
component is only wrapped with SomeContextProvider (does this mean that the child is consuming the context?)
Here is the scenario:
- When
Parent
is re-rendered, theChild
is also re-rendered even if theChild
does not consume theSomeContext
andpropsAreEqual
returnstrue
. - When I move
Child
to outside scope,React.memo
works as expected and prevents re-rendering ofChild
whenParent
is re-rendered.
How come Child
is re-rendered while it is not consuming the context? Isn't React.memo
supposed to prevent re-renders? What do I miss about these concepts?