Reputation: 1013
A React Copmponent is rendering when its state or propr remain the same. I don't get why it does it rerender/update since the result wouldn't change
class A extends Component {
render() {
console.log("Hello")
return "Foo";
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = { a: "ASDA" };
}
render() {
return (
<div>
<button onClick={()=>this.setState({a: Math.random()}) }>asdsa</button>
<div>{this.state.a}</div>
<A />
</div>
);
}
Whenever I click the button, component A is rerendered (I can see "hello" in the console) I thought React was avoiding many useless rerenderings.
Upvotes: 3
Views: 1094
Reputation: 2964
Your parent component is re-rendering because its state changes.
When a component re-renders, all its children are re-rendered. This means that the render function runs, and the result is added to the virtual DOM.
This result is then compared with the existing DOM. It doesn't mean that that actual DOM changes for the child components, just that they are re-evaluated because the DOM might need to change.
If it turns out that the child element does need to change, then that element in the actual DOM is re-rendered. If the child element doesn't need to change, that element in the DOM remains un-effected.
This is generally fine and has minimal to no performance impacts for small components, so usually you don't need to worry about it.
If you have deep component hierarchies or components with complex render functions that perform computationally expensive operations, consider using React.memo
if you feel that the render cycle is causing a hit on performance.
Upvotes: 6