Wednesday, July 21, 2021

What are the difference between componentDidMount() and componentDidUpdate()

 Ans:-

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;

No comments:

Post a Comment