React - componentDidMount and componentWillUnmount (class component)

0 points
Created by:
Dirask Community

In this article, we would like to show you how to handle mount and unmount events in React working with class components.

In React class components we can handle mount or unmount actions with two methods:

  • componentDidMount()¬†-¬†that gets invoked right after a¬†React¬†component has been mounted (right after the first render()),
  • componentWillUnmount()¬†-¬†the last function¬†called immediately before the component is removed from the DOM.

Practical example:

// ONLINE-RUNNER:browser;

// Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

class MyComponent extends React.Component {
  componentDidMount() {
    console.log('MyComponent onMount');

  componentWillUnmount() {
    console.log('MyComponent onUnmount');

  render() {
    return (

class App extends React.Component {
  constructor(props) {
    this.state = {
      visible: true

  render() {
    return (
        <button onClick={() => this.setState({ visible: true })}>
          Mount MyComponent
        <button onClick={() => this.setState({ visible: false })}>
          Unmount MyComponent
        {this.state.visible && <MyComponent />}

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);


Go to this article to see functional component example.


React - componentDidMount and componentWillUnmount (class component)
Native Advertising
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

‚̧ԳŹūüíĽ ūüôā