DEV Community 👩‍💻👨‍💻

Joy Dey
Joy Dey

Posted on

React Life Cycle - Mounting

React a lifecycle is an event that is used to operate components throughout the duration of the Document Object Model. It has mainly three phases -

Mounting - It means putting elements on the dom.
Updating - Whenever the components state and props are changed, the component updated
Unmounting - When a component is removed from the dom, then this lifecycle method happens

Today we are discussing the mounting phase.

Mounting
In mounting, there are some built-in methods called. they are-

1. constructor() - when the component is initiated, The constructor method is called before anything else. In this method, props are passed as an argument. To inherit methods from its parent, we should call super(props) before anything else.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

2. render()- render method outputs the HTML to the Browser DOM.

class Header extends React.Component {
  render() {
    return (
      <h1>This is the content of the Header component</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

3. componentDidMount() - The componentDidMount method is called after the component is rendered.

class Header extends React.Component {
  constructor(props) {
    super(props);
    this.state = {favoritecolor: "red"};
  }
  componentDidMount() {
    setTimeout(() => {
      this.setState({favoritecolor: "yellow"})
    }, 1000)
  }
  render() {
    return (
      <h1>My Favorite Color is {this.state.favoritecolor}</h1>
    );
  }
}

ReactDOM.render(<Header />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

We are hiring! Do you want to be our Senior Platform Engineer? Forem is hiring a Senior Platform Engineer

If you're interested in ops and site reliability and capable of dipping in to our Linux stack, we'd love your help shoring up our systems!