Controlling re-renders in react?

47 views Asked by At

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.

0

There are 0 answers