0

I have been given the task to use a react lifecycle method *other* than shouldComponentUpdate() to control re-rendering of a component. Just like how shouldComponentUpdate() can prevent re-renders if you return false, I should be able to use one of the other lifecycle methods (like componentWillUpdate(), componentDidUpdate() maybe?) to prevent re-renders if the state is the same as the previous state.

Is this possible? If so, how?

I have this type of a setup:

class App extends Component {
  constructor() {
    super();
    this.state = {
      text: "",
      someStateProperty: "abcd"
    };
  }

  // shouldComponentUpdate(nextProps, nextState) {
  //   if (this.state.someStateProperty !== nextState.someStateProperty)
  //     return true;
  //   return false;
  // }

  render() {
    console.log("render");
    return (
      <input
        value={this.state.text}
        type="text"
        onChange={(e) => this.setState({ text: e.target.value })}
      />
    );
  }
}

In the above code, I am updating this.state.text while keeping this.state.someProperty the same.

shouldComponentUpdate() is called every time there is a call to this.setState and returns false due to the comparison inside, preventing the re-rendering of the input component because there is no change in this.state.someProperty.
This prevents the render() function from running again and I do not get render logged in the console.

So is there another lifecycle method that can replicate this sort of behavior?

I have also created a sandbox/playground of it here.

De-J
  • 1
  • 2
  • There is no reason to use another lifecycle method. You could just change the logic `return nextProps.someStateProperty !== this.state.someStateProperty || nextProps.text !== this.state.text`. However if you simply don't want to re-render the component if no state changes or prop changes are made you should probably just inherit from [`PureComponent`](https://react.dev/reference/react/PureComponent) rather then [`Component`](https://react.dev/reference/react/Component). – 3limin4t0r Jul 28 '23 at 08:21
  • I've suggested `shouldComponentUpdate()` and `PureComponent` but my senior insists that there is another way/lifecycle method. – De-J Jul 28 '23 at 08:31
  • Maybe they are talking about invoking [`forceUpdate()`](https://react.dev/reference/react/Component#forceupdate) somewhere, but that seems like a strange thing to do in this scenario. – 3limin4t0r Jul 28 '23 at 08:37
  • The example they gave me was similar to the one I have given. They said that I should be able to not re-render if after calling `setState` , the state didn't actually change. – De-J Jul 28 '23 at 09:00

0 Answers0