To control your component use shouldComponentUpdate
(link for the article). It has 2 arguments nextProps and nextState. You can compare this.state.field
and nextState.field
and if they are different make side effect:
class ClickButton extends React.Component {
constructor(props) {
super(props);
this.state = {class: "off", label: "press"};
this.press = this.press.bind(this);
}
shouldComponentUpdate(nextProps, nextState){
if(nextState.class !== this.state.class){
return true
}
return false;
}
press(){
var className = (this.state.class==="off")?"on":"off";
this.setState({class: className});
}
render() {
return <button onClick={this.press} className={this.state.class}>{this.state.label}</button>;
}
}
If ypu return true from this method, it says React that component should update, false in other way, Component won't update.
Also you can extends from PureComponent
(PureComponent), it will be automatically follow props and state:
class ClickButton extends React.PureComponent {
constructor(props) {
super(props);
this.state = {class: "off", label: "press"};
this.press = this.press.bind(this);
}
press(){
var className = (this.state.class==="off")?"on":"off";
this.setState({class: className});
}
render() {
return <button onClick={this.press} className={this.state.class}>{this.state.label}</button>;
}
}
But it makes a superficial comparison (by reference). If you have nested fields in you state, and they are changing, PureComponent doesn't rerender Component.
There are other methods like componentDidUpdate
(link) and componentDidMount
(link). First, called when component rerender:
componentDidUpdate(prevState) {
if (this.state.userID !== prevState.userID) {
this.fetchData(this.state.userID);
}
}
Talking about second one, it will be called when component set in the DOM.
In your case use componentDidUpdate