EN
React - onMount and onUnmount component (functional components)
10
points
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);