How to do Mounting and Unmounting in ReactJS

Today in this tutorial, we will learn how to do mounting and unmounting in ReactJS. A React component’s life-cycle have different phases for creation and deletion. In coding terms, these are known as mounting and unmounting. In other words, you can also say that “Setup” and “Cleanup”.

Phases which we are using in Setup and Cleanup:

In the mounting or setup phase, we have access to two life-cycle methods: componenetWillMount and componentDidMount. And in the unmounting or cleanup phase, we have just one life-cycle method: componenetWillUnmount.

How it is Working?

The mounting and unmounting phases are important to confirm that the React component gets set up and initialized easily and when it finally unmounted. And it leaves the space it occupied just as same as before.

In the mounting phase, we can set up any special requirements we may have for any particular component like fetch some data, start counters and many more. It is very important to clean all the things we have set up in the unmounting stage in, componentWillUnmount as not doing so it may end pretty bad – your application can crash also.

Code for mounting and unmounting in ReactJS:

<!DOCTYPE html>
    <meta charset="UTF-8">
    <title> ReactJS </title>
    <script src=""> </script>
    <script src=""> </script>
    <script src=""> </script>
    <div id="app"></div>
    <script type="text/babel">
    var LifecycleComponent = React.createClass({
      increment: function() {
          count: this.state.count + 1
      getDefaultProps: function() {
        console.log("Getting our default properties");
      getInitialState: function() {
        console.log("Getting our initial state");
          count: 0
      componentWillMount: function() {
        console.log("Component is mounting");
      render: function() {
        console.log("Component is rendered");
        return (
          <button className="btn royblue-btn" onClick={this.increment}>{this.state.count}</button>
      componentDidMount: function() {
        console.log("Component has rendered");
        this.interval = setInterval(this.increment, 1000);
      componentWillUnmount: function() {
        console.log('Component Unmounted!');

    var LifecycleContainer = React.createClass({
        mount: function() {
            <LifecycleComponent />,
        unmount: function() {
        render: function() {
          console.log("LifecycleContainer Rendered");
            <div className="container">
              <button className="btn green-btn" onClick={this.mount}>Mount</button>
              <button className="btn red-btn" onClick={this.unmount}>Unmount</button>
              <div id="renderHere"></div>
      <LifecycleContainer />,

You may also learn

Leave a Reply

Your email address will not be published. Required fields are marked *