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
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
componentWillReceiveProps - as the function name states this is called whenever new props will be passed to the component and you can trigger an action depending on the new prop state
shouldComponentUpdate - is a filter function which decides if the component tree should be re-rendered. This function can serve as an additional filter where you change are happening which don't require a re-render
More info here
© 2022 - 2024 — McMap. All rights reserved.
shouldComponentUpdate
is used for you to accept or decline an update. If a prop changes, you might not want to render the component again, so you would return false. componentWillReceiveProps is a way for you to check what props you currently have and what the next props are going to be.componentWillReceiveProps(nextProps) {}
. – Cleave