Languages
[Edit]
EN

React - onMount and onUnmount component (functional components)

10 points
Created by:
Kate_C
22390

In this short article we would like to show how to handle mount and unmouont 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);

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