4

let say I have a functional Home component:

const Home = () => {
  console.log('outside useEffect')
  useEffect(() => {
    console.log('inside useEffect')
    
    // cleanup function
    return () => { console.log('unmounted') }
  }, [])

  return <div>Hello Word</div>
}

The output in the console shows:

outside useEffect
inside useEffect
unmounted
inside useEffect

My questions are:

  1. When does the component unmount, does it happen automatically after it has rendered once or when?
  2. What exactly does happen when the component unmounts? Does the component get deleted/removed? If yes then how am I still able to see the Hello World even if it unmounts.
Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65

2 Answers2

3

Normally a component gets unmounted when for example it's rendered conditionally and the conditional become false. DummyComponent below gets unmounted every time state become false. And when a component is unmounted, it's removed from the DOM, and therefore you won't see it in the page.

const DummyComponent = () => {
  useEffect(() => {
    console.log("mounted");
    return () => {
      console.log("unmounted");
    };
  }, []);
  return <div>Hello Word</div>;
};

const App = () => {
  const [state, setState] = useState(true);
  return (
    <div>
      <button onClick={() => setState(!state)}>Toggle Dummy Component</button>
      {state ? <DummyComponent /> : <></>}
    </div>
  );
};

What you have right now is introduced by React v18 where each component gets mounted and immediately unmounted and mounted again, when you are in strict development mode. I explained the reason why in this QA on Stack Overflow. And it's so quick that you are not noticing. The production mode is as before, explained in the first section.

Youssouf Oumar
  • 29,373
  • 11
  • 46
  • 65
0

In React 18 Strict Mode, each component is unmounted & remounted again.
https://reactjs.org/blog/2022/03/29/react-v18.html

Perhaps that's why "inside useEffect" is printed after "unmount".

Nice Books
  • 1,675
  • 2
  • 17
  • 21