Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is difference between componentDidMount and componentDidUpdate in react native

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?

like image 942
Mohammadhossein ahmadi Avatar asked Feb 22 '19 23:02

Mohammadhossein ahmadi


2 Answers

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.

like image 188
Nino Filiu Avatar answered Sep 27 '22 17:09

Nino Filiu


componentDidMount()

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()

componentDidUpdate() is invoked immediately every time the updating occurs. This method is not called for the initial render.

You can understand more from this below example

import React from 'react';

class Example extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      count: 0
    };
  }
  componentDidMount() {

    //This function will call on initial rendering.
    document.title = `You clicked ${this.state.count} times`;

  }
  componentDidUpdate() {
     document.title = `You clicked ${this.state.count} times`;
   }

  render(){
    return(
      <div>
      <p>You clicked {this.state.count} times</p>
      <button onClick={() => this.setState({ count: this.state.count + 1 })}>
        Click me
      </button>
    </div>
    )
  }
}
export default Example;

You can understand by commenting and un-commenting both life cycle methods.

like image 35
Muhammad Usama Rabani Avatar answered Sep 27 '22 16:09

Muhammad Usama Rabani