Languages
[Edit]
EN

React - componentDidMount and componentWillUnmount (class component)

0 points
Created by:
Hayley-Mooney
647

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 (
      <p>MyComponent</p>
    );
  }
}

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

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

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

Note:

Go to this article to see functional component example.

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

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.

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

Join