Reputation: 1517
As I have shown in below, react child renders every time it's parent renders. Why is that and is that an issue? Also how can I avoid it such that child re renders only when it's pros change.
import React, {useEffect, useState} from 'react';
function App() {
return (
<div>
<Main></Main>
</div>
);
}
export default App;
function Main() {
const [count, updateFlag] = useState(0);
function onButtonClick(newCount) {
updateFlag(newCount);
}
return (
<div>
<button onClick={()=>onButtonClick(count + 1)}>Main Button {count}</button>
<Sub>ds</Sub>
</div>
);
}
function Sub() {
useEffect(() => {
console.log('useEffect called');
});
return(
<div>This is sub</div>
);
}
Upvotes: 1
Views: 116
Reputation: 282120
The virtual DOM implemented in React works in this way. When a parent updates all child elements are also updated
You can prevent child elements from re-render if the props do not change for them using React.memo
for functional components and by extending PureComponent
for class components. You could also implement a custom shouldComponentUpdate
method in class component for more finegrained controlling
Changing to the below code for Sub component will not re-render it if the parent updated. This is because no props are passed to it and hence nothing changes for this component. If props are passed React.memo performs a shallow comparison before deciding to trigger render. You can also pass in the second parameter to React.memo
for finegrained controlling
const Sub = React.memo(() {
useEffect(() => {
console.log('useEffect called');
});
return(
<div>This is sub</div>
);
})
Upvotes: 1