shouldComponentUpdate() in ReactJS

shouldComponentUpdate(nextProps, nextState) is called before render() is called ( not the first time ).

shouldComponentUpdate() method questions, should the component updated? This method returns true or false. If it returns true, then component will be rendered. If returns false, component will not be rendered.

shouldComponentUpdate(nextProps, nextState) provides nextProps and nextState as parameters. You can compare it and return true or false.

Why shouldComponentUpdate() should be used?

shouldComponentUpdate() is used for performance optimization because you can stop re-rendering if there is no change.

Points to remember while using shouldComponentUpdate()

There are many points that you should remember while using shouldComponentUpdate() method.

  • shouldComponentUpdate() should not be used to stop rendering becuase that will lead to some bugs. You should use PureComponent which performs a shallow comparision of props and state.
  • If you are writing shouldComponentUpdate(), then you should not do deep comparing or use JSON.stringify() because that will degrade performance.
  • shouldComponentUpdate() method will not be called when you use Component.forceUpdate() or when component is rendered for the first time.
  • If shouldComponentUpdate() method returns false, that means component will not render but its child component will be rendered if state of child component changes.
  • In version => 16.3, if shouldComponentUpdate() returns false, then UNSAFE_componentWillUpdate(), render() and componentDidUpdate() methods will not be called.

Conclusion

In this section, we learned about shouldComponentUpdate() method and for what it can be used.
In the next section, you will learn about getSnapshotBeforeUpdate() method of ReactJS component.