Languages
[Edit]
EN

React - useEffect cleanup on component unmount only

3 points
Created by:
Lani-Skinner
748

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 username changes - the effect is fired when the MyComponent is mounted and on every username change,
  • the second one (with an empty array of dependencies) - calls the function which is being called when MyComponent is 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);

Alternative titles

  1. React - useEffect cleanup for componentWillUnmount only
  2. React - useEffect cleanup only when unmounting a component
  3. React - component destructor
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.
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