Reputation: 5123
<Parent P={some_state} >
<Child />
<Parent />
If some_state
changes, causing the Parent
to re-render, does it know to leave Child
alone?
Upvotes: 0
Views: 141
Reputation: 2849
I think what you are looking for is React.memo
. Memoizing a component tells the component not to change or render unless the props it cares about changes or it has it's own internal changes.
In your example, if someState
changes in the <Parent />
the <Child />
will render again. To fix that we can memoize our child.
// Child Component
import React, { useEffect } from "react";
const Child = () => {
useEffect(() => console.log("Child rendered")); // simple way of logging each time the component renders
return (
<span>
I take no props, I shouldn't update unless my local state changes
</span>
)
};
const MemomizedChild = React.memo(Child);
// Parent Component
const Parent = ({ someState }) => {
return (
<MemomizedChild />
)
};
// Parent of Parent Component
import { useEffect, useState } from "react";
const App = () => {
const [foobar, setFoobar] = useState("hello");
useEffect(() => {
setTimeout(() => setFoobar("world"), 5000)
}, []) // after 5 seconds change the state variable to "world"
return (
<Parent someState={foobar} />
)
}
Explanation
Here are the steps or chain of events in that example:
foobar
(just to trigger a prop change in the Parent component)someState
will change
If we use the non memoized Child component the "Child rendered" console log will fire twice, once on mount and the second time when the Parent props change.
Upvotes: 2