Arnaud Rochez Arnaud Rochez - 25 days ago 5
React JSX Question

Is there a way to change an html line instead of rerendering the whole component?

I am new to react and was wondering if there was a way to change one html line every second in the render method for example instead of rerendering the whole component?

I have to make a status bar where the time is displayed, so the date needs to be updated every second. Is it possible to only change the Menubar-time div?

componentDidMount: function() {
const self = this;
self.interval = setInterval(function() {
self.setState({
now: new Date(),
});
}, 1000);
},

componentWillUnmount: function() {
clearInterval(this.interval);
},


render() {
return (
<div className="Menubar">
<div className="Menubar-name">
<p>{this.state.login}</p>
</div>
<div className="Menubar-date">
<p><Time value={this.state.now} format="DD/MM/YYYY" /></p>
</div>
<div className="Menubar-time">
<p><Time value={this.state.now} format="HH:mm:ss" /></p>
</div>
</div>
);
},


Thank you for your answers.

Answer

Actually, the whole component is not re-rendered. render() returns instance of virtual DOM and only difference between current DOM and new DOM(returned by a render()) is applied. So you do not need to worry about performance in this case.

When you feel your performance being poor, you may consider implementing shouldComponentUpdate. As for me, I had to implement this just once or twice. React itself needs optimizations in quite rare cases.

Good luck!