0

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.

Nil
  • 1,209
  • 9
  • 20
De-J
  • 1
  • 2

1 Answers1

1

If you are using functional components, you can use React.memo to achieve this.

import React, { useState, memo } from 'react';

const App = () => {
  const [value, setValue] = useState("abcd");

  const handlePress = () => {
    setValue("abcd");
  };

  console.log("render");

  return (
    <div>
      <h1>{value}</h1>
      <button onClick={handlePress}>Press</button>
    </div>
  );
};

export default memo(App);

For class components, you can use shouldComponentUpdate, but you'd have to manually compare the changes.

shouldComponentUpdate(nextProps, nextState) {
  return nextState.value !== this.state.value;
}

Edit

React.memo only tracks the props, not state.

Thanks @Oktay Yuzcan for pointing it out.

Audun Hilden
  • 330
  • 3
  • 13