Reputation: 2878
I have a react component, that I noticed is being rerendered every time the owner component renders, even though the props being passed have not changed.
Is this normal behavior? I thought a component only rerenders if the owner sends in new props, i.e. the props are changed have different values or some internal state changes.
Assuming the above is true are there any tricks to debugging what is changing to cause the component to rerender?
Upvotes: 2
Views: 1963
Reputation: 131
The whole point of React is to use Virtual DOM above actual DOM. render()
method in your React Component is used to compute new VD, compare it with previous, and apply diff to AD. And there is a difference between e.g. React.DOM.div
and your component in the render()
method of another component - React needs to calculate VD of your component - obviously, due it's render()
method - even if no props were passed.
However, you can explicitly tell React Component, should it invoke it's render()
method or not - using the shouldComponentUpdate()
hook. In React.createClass()
notation you can use PureRenderMixin
, which is nothing except next code injection:
import shallowEqual from 'react/lib/shallowEqual';
shouldComponentUpdate(nextProps, nextState) {
return !shallowEqual(nextProps, this.props) || !shallowEqual(nextState, this.state);
}
There are some ways to do it in ES6 notation - e.g. inheritance from PureRenderComponent
, that contains the above hook.
See also https://facebook.github.io/react/docs/advanced-performance.html
Upvotes: 4