Reputation: 1
simple and silly code, but for some reason the console.log("hi") happens twice. i tried to create the usual todo-list project but my program double clicked everything, so i texted and reached this point - this code execute any JS a the render method - twice.
anyone knows why?
import React from 'react';
import './App.css';
class App extends React.Component {
render(){
return (
<div className="App">
{console.log("hi")}
</div>
);
}
}
export default App;
Upvotes: 0
Views: 70
Reputation: 5854
Re-rendering happened some time. In many cases it’s not a problem, but if the slowdown is noticeable, you can override the lifecycle function shouldComponentUpdate, which is triggered before the re-rendering process starts. If you know that in some situations your component doesn’t need to update, you can return false from shouldComponentUpdate instead, to skip the whole rendering process, including calling render() on this component and below.
In most cases, instead of writing shouldComponentUpdate() by hand, you can inherit from React.PureComponent. It is equivalent to implementing shouldComponentUpdate() with a shallow comparison of current and previous props and state.
Here is an example found from reacjs.org
Example
class CounterButton extends React.Component {
constructor(props) {
super(props);
this.state = {count: 1};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.color !== nextProps.color) {
return true;
}
if (this.state.count !== nextState.count) {
return true;
}
return false;
}
render() {
return (
<button
color={this.props.color}
onClick={() => this.setState(state => ({count: state.count + 1}))}>
Count: {this.state.count}
</button>
);
}
}
Upvotes: 1