Languages
[Edit]
EN

React - useEffect cleanup on component unmount only

3 points
Created by:
Lani-Skinner
438

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);
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