Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS: What is the difference between componentDidUpdate and the second parameter of setState?

Is there any difference between those 2 functions? (besides their arguments) It seems like those methods have the same triggers, isn't it?

Appreciate your help :)

like image 441
Eran Amar Avatar asked Apr 22 '15 13:04

Eran Amar


People also ask

What is the second parameter in setState?

The second parameter to setState() is an optional callback function that will be executed once setState is completed and the component is re-rendered. componentDidUpdate should be used instead to apply such logic in most cases. You may directly pass an object as the first argument to setState instead of a function.

Is componentDidUpdate called after setState?

You may call setState() immediately in componentDidUpdate() but note that it must be wrapped in a condition like in the example above, or you'll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance.

What is the difference between componentDidUpdate method and componentDidMount method?

componentDidMount() will be rendered immediately after a component is mounted. This method will render only once and all the initialization that requires DOM nodes should go here. Setting state in this method will trigger a re-rendering. componentDidUpdate() is invoked immediately every time the updating occurs.

What is componentDidUpdate in React?

The componentDidUpdate() method allows us to execute the React code when the component is updated. All the network requests that are to be made when the props passed to the component changes are coded here.


1 Answers

componentDidUpdate is called whenever the component has re-rendered, which might be caused by either:

  • a change in state
  • a call to forceUpdate
  • a parent component re-rendering (or another call to React.render in the case of the top-level component)

The setState callback will only be called once the state transition has completed and the component has re-rendered.

like image 144
Alexandre Kirszenberg Avatar answered Oct 24 '22 06:10

Alexandre Kirszenberg