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
false. If it returns
true, then component will be rendered. If returns
false, component will not be rendered.
shouldComponentUpdate(nextProps, nextState) provides
nextState as parameters. You can compare it and return
Why shouldComponentUpdate() should be used?
shouldComponentUpdate() is used for performance optimization because you can stop re-rendering if there is no change.
shouldComponentUpdate() is not called in mounting phase. That means, it is not called when component renders first time. It will always be called when component re-renders.
Points to remember while using shouldComponentUpdate()
There are many points that you should remember while using
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
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.
false, that means component will not render but its child component will be rendered if
stateof child component changes.
In version => 16.3, if
false, then UNSAFE_componentWillUpdate(), render() and componentDidUpdate() methods will not be called.
Right now, if
false, ReactJS takes it as a firm no to render. But in future, ReactJS may take
false as just hint. So returning
false may still re-render the component.
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.