Is there a react lifecycle method that we can use to perform a re-render only when the updated state is different from the previous state. For example, in the following code:
class App extends Component {
constructor() {
super();
this.state = {
value: "abcd"
};
}
handlePress = () => {
this.setState({ value: "abcd" });
};
render() {
console.log("render");
return (
<div>
<h1>{this.state.value}</h1>
<button onClick={this.handlePress}>Press</button>
</div>
);
}
}
You can see that on pressing the button, even though the state is the same as the previous, it will still lead to the render()
function running.
I know that we can use shouldComponentUpdate()
or PureComponent
to prevent that but are there other ways/lifecycle methods that can achieve this?
I have also created a sandbox/playground of the above code here.