when i use react ,i find these two life cycle are too similar, componentWillReceiveProps receive nextProps as argument, shouldComponentUpdate receive nextProps and nextState as arguments, so i think shouldComponentUpdate can do the same thing and more, why react keep componentWillReceiveProps method, i wonder what's difference between these two methods
What does “shouldComponentUpdate” do and why is it important ? The shouldComponentUpdate is a lifecycle method in React. This method makes the component to re-render only when there is a change in state or props of a component and that change will affect the output.
The componentWillReceiveProps() is invoked before our mounted React component receives new props. It is called during the updating phase of the React Life-cycle. It is used to update the state in response to some changes in our props.
The shouldComponentUpdate method is majorly used for optimizing the performance and to increase the responsiveness of the website but do not rely on it to prevent rendering as it may lead to bugs.
The render() method is required and will always be called, the others are optional and will be called if you define them.
They have two different roles and execute on different situations:
shouldComponentUpdate
will be called every time a prop or something in the state changes (or React think that has changed). It's function is to determine if the component should re-render by returning a boolean: true
if the component should re-render (this is the default return value), or false
if it shouldn't.
You can access the current and next state and props, to compare and decide if it really should re-render or not. You should not use this method for other reason.
On the other side, componentWillReceiveProps
will only be called if the props changed (or seem to have changed). If only the state changes, this method won't be called.
Also, this won't decide if the component should re-render. You can use this method to, for example, change some state, or make an API call.
Check out these links:
componentWillReceiveProps
: https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/component_will_receive_props.html
shouldComponentUpdate
: https://developmentarc.gitbooks.io/react-indepth/content/life_cycle/update/using_should_component_update.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With