Monday, December 4, 2023
126
rated 0 times [  131] [ 5]  / answers: 1 / hits: 13917  / 5 Years ago, fri, february 22, 2019, 12:00:00

I cant understand what is difference between componentDidMount and componentDidUpdate


I saw some counter app that use setState method for increasing count value inside componentDidMount so what if we write setState inside componentDidUpdate?


and when should we use componentDidMount or componentDidUpdate?


More From » react-native

 Answers
1

From the docs on the component lifecycle:




  • componentDidMount(): invoked immediately after a component is mounted (inserted into the DOM tree)

  • componentDidUpdate(prevProps, prevState, snapshot): is invoked immediately after updating occurs. This method is not called for the initial render. Use this as an opportunity to operate on the DOM when the component has been updated.



To make it simple, the first is called at the beginning, and the second upon every change. They are absolutely not interchangeable.



About using setState inside componentDidUpdate: beware! Using setState calls componentDidUpdate, so you might end up with an infinite loop if you call setState at *every invocation of componentDidUpdate.



Oh and also, here's a cool diagram to sum up the whole component lifecycle.


[#8772] Thursday, February 21, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
mackenzihannal

Total Points: 548
Total Questions: 96
Total Answers: 96

Location: Lithuania
Member since Fri, Sep 4, 2020
3 Years ago
mackenzihannal questions
Fri, Apr 22, 22, 00:00, 2 Years ago
Sun, Feb 21, 21, 00:00, 3 Years ago
Sat, Oct 12, 19, 00:00, 4 Years ago
Thu, Aug 29, 19, 00:00, 4 Years ago
Wed, Jan 2, 19, 00:00, 5 Years ago
;