Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why React keep componentWillReceiveProps and shouldComponentUpdate methods both?

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

like image 773
2014 Avatar asked Nov 28 '17 12:11

2014


People also ask

Why do we use shouldComponentUpdate () function in ReactJS?

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.

When should I use componentWillReceiveProps?

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.

When should you use shouldComponentUpdate?

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.

Which is the only compulsory method required by React?

The render() method is required and will always be called, the others are optional and will be called if you define them.


1 Answers

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

like image 116
Facundo Matteo Avatar answered Sep 24 '22 04:09

Facundo Matteo