EN
React - useEffect cleanup on component unmount only
3
points
In this article, we would like to show you how to make useEffect cleanup only when the component is unmounted in React.
Below we create MyComponent which uses two useEffect hooks:
- the first one to monitor
usernamechanges - the effect is fired when theMyComponentis mounted and on everyusernamechange, - the second one (with an empty array of dependencies) - calls the function which is being called when
MyComponentis unmounted.
Runnable example:
// ONLINE-RUNNER:browser;
// Note: Uncomment import lines while working with JSX Compiler.
// import React from 'react';
const MyComponent = () => {
const [username, setUsername] = React.useState('example_username');
React.useEffect(() => {
console.log('effect: called when username initialized or changed.');
}, [username]);
React.useEffect(() => {
return () => {
console.log('cleanup: called when MyComponent unmounted');
};
}, []);
const handleUsernameChange = (event) => {
setUsername(event.target.value);
};
return (
<div style={{border: '1px solid red'}}>
<div>
Current username:
<input value={username} onChange={handleUsernameChange} />
</div>
<div>Current username: {username}</div>
</div>
);
};
const App = () => {
const [componentMounted, setComponentMounted] = React.useState(true);
const handleUnmountClick = () => {
setComponentMounted(false);
};
return (
<div>
{componentMounted ? <MyComponent /> : null}
<br />
<button onClick={handleUnmountClick}>Unmount MyComponent</button>
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root);