We have ‘componentWillUpdate’ and ‘componentWillUpdate’ logs in our console, this shows that our component is re-rendering even if when the state is the same. This is called wasted renders.

Pure Component/shouldComponentUpdate

In in order to stave wasted renders in our React Components, we would hook into the shouldComponentUpdate lifecycle method.

The shouldComponentUpdate method is the lifecycle method that React calls when it wants to render a component, this method gives it the go-ahead or stop signal to or not render a component.

If we have our shouldComponentUpdadte like this:

shouldComponentUpdate(nextProps, nextState) {

return true

}

nextProps : The next props value the component will receive.

: The next value the component will receive. nextState : The next state value the component will receive.

With this above, we are telling React to render our component. This is so because it returns true.

If we write it like this:

shouldComponentUpdate(nextProps, nextState) {

return false

}

We are telling React never to render the component. This is so because it returns false.

So whenever you want to render your component, you have to return true. Now, we could re-write our TestC component:

import React from 'react'; class TestC extends React.Component {

constructor(props) {

super(props);

this.state = {

count: 0

}

} componentWillUpdate(nextProps, nextState) {

console.log('componentWillUpdate')

} componentDidUpdate(prevProps, prevState) {

console.log('componentDidUpdate') }

shouldComponentUpdate(nextProps, nextState) {

if (this.state.count === nextState.count) {

return false

}

return true

} render() {

return (

<div>

{ this.state.count }

<button onClick = {

() => this.setState({ count: 1 }) }> Click Me </button>

</div>

);

}

} export default TestC;

See, we added shouldComponentUpdate in our TestC component, We checked if the count value in the current state object this.state.count is equal === to the count value in the next state nextState.count object. If they are equal therefore no re-render should occur so we return false, if they are not equal we return true so re-rendering should occur to display the new value.

Testing it out in our browser, we see our initial rendering: