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.
If you are using functional components, you can use
React.memoto achieve this.For class components, you can use
shouldComponentUpdate, but you'd have to manually compare the changes.Edit
React.memo only tracks the props, not state.
Thanks @Oktay Yuzcan for pointing it out.