Reputation: 4533
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",
Upvotes: 0
Views: 563
Reputation: 1032
During an update, shouldComponentUpdate
is called before the render method is. It tells the component if it needs to re-render. And if shouldComponentUpdate
returns false, the component is not re-rendered.
In your case,
shouldComponentUpdate ( nextProps, nextState ) {
console.log( 'In shouldComponentUpdate', nextProps, nextState );
return false;
}
The console.log
is triggered, but since you are returning false, the component wont re-render after that.
You can check it from the example here:
The count doesn't increment when you return false in componentShouldUpdate
and increments when you return true.
Upvotes: 0
Reputation: 53874
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>
);
}
}
Upvotes: 1