Search code examples
reactjslifecycle

Why shouldComponentUpdate hook is not working in React?


I have started learning react.js and in its lifecycle, I got this shouldComponentUpdate method. And in return, I'm passing false still it affects dom. And in my reference video it's not affecting to the dom.

Above render()

shouldComponentUpdate ( nextProps, nextState ) {
    console.log( 'In shouldComponentUpdate', nextProps, nextState );        
    return false;
}

I'm using this version : "react": "^16.9.0",


Solution

  • shouldComponentUpdate lifecycle fire ups on every component render.

    In your case, if you want it to log something, you need to make component render, via its father (rendering the father so it render its children) or via self renders, for example changing its state:

    export default class App extends React.Component {
      state = { counter: 0 };
      shouldComponentUpdate(nextProps, nextState) {
        console.log('In shouldComponentUpdate', nextProps, nextState);
        return false;
      }
    
      render() {
        return (
          <FlexBox>
            <Button onClick={() => this.setState({ counter: this.counter + 1 })}>
              Counter
            </Button>
          </FlexBox>
        );
      }
    }
    

    Edit Q-57871306-ShouldComponentUpdate