Languages
[Edit]
EN

React - onMount and onUnmount component (functional components)

10 points
Created by:
Adnaan-Robin
724

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

In Functional React we can handle mount or unmount actions for any component with useEffect hook.

It is necessary to insert at beginning of our component following code:

React.useEffect(() => {
    console.log('MyComponent onMount');
    return () => {
        console.log('MyComponent onUnmount');
    };
}, []);

Note: it is very important to call useEffect with empty dependences: [].

 

Practical example

// ONLINE-RUNNER:browser;

//import React from 'react';
//import ReactDOM from 'react-dom';

const MyComponent = () => {
	React.useEffect(() => {
      	console.log('MyComponent onMount');
      	return () => {
        	console.log('MyComponent onUnmount');
        };
    }, []);
    return (
      <div>Component body here...</div>
    );
};

const App = () => {
    const [visible, setVisible] = React.useState(false);
    return (
      <div>
        <button onClick={() => setVisible(true)}>Mount MyComponent</button>
        <button onClick={() => setVisible(false)}>Unmount MyComponent</button>
        {visible && <MyComponent />}
      </div>
    );
};

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

Alternative titles

  1. React - mount and unmount component events (functional components)
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 - onMount and onUnmount (functional components)
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