Languages
[Edit]
EN

React - useEffect cleanup on component unmount only

0 points
Created by:
Admin Dirask Community
1420

In this article, we would like to show you how to make useEffect cleanup only when the component unmounts in React.

Below we create MyComponent which uses two useEffect hooks:

  • first useEffect - for monitoring the username change, so the effect is fired when component mounts and on every username change,
  • second useEffect (with empty array of dependencies) - contains the cleanup function which is being called when MyComponent unmounts.

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');
  }, [username]);

  React.useEffect(() => {
    return () => {
      console.log('cleanup');
    };
  }, []);

  const handleUsername = (event) => {
    const { value } = event.target;

    setUsername(value);
  };

  return (
    <div>
      <h3>{username}</h3>
      <div>
        <input value={username} onChange={handleUsername} />
      </div>
    </div>
  );
};

function App() {
  const [shouldRender, setShouldRender] = React.useState(true);

  const handleClick = () => {
    setShouldRender(false);
  };

  return (
    <div>
      {shouldRender ? <MyComponent /> : null}
      <div>
        <button onClick={handleClick}>Unmount</button>
      </div>
    </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