Does React re-render all components and sub components every time setState()
is called?
If so, why? I thought the idea was that React only rendered as little as needed - when state changed.
In the following simple example, both classes render again when the text is clicked, despite the fact that the state doesn't change on subsequent clicks, as the onClick handler always sets the state
to the same value:
this.setState({'test':'me'});
I would've expected that renders would only happen if state
data had changed.
Here's the code of the example, as a JS Fiddle, and embedded snippet:
var TimeInChild = React.createClass({
render: function() {
var t = new Date().getTime();
return (
<p>Time in child:{t}</p>
);
}
});
var Main = React.createClass({
onTest: function() {
this.setState({'test':'me'});
},
render: function() {
var currentTime = new Date().getTime();
return (
<div onClick={this.onTest}>
<p>Time in main:{currentTime}</p>
<p>Click me to update time</p>
<TimeInChild/>
</div>
);
}
});
ReactDOM.render(<Main/>, document.body);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.0.0/react-dom.min.js"></script>
setState()
even with dummy data does cause the element to render differently so I would say yes. Absolutely it should try to re-render your object when something might have changed because otherwise your demo - assuming it was the intended behaviour - wouldn't work! – Tadhg McDonald-JensenshouldComponentUpdate
method, which I assumed a simple version of it must already be included in React itself. Sounds like the default version included in react simply returnstrue
- which forces the component to re-render every single time. – Brad Parks