What exactly does it mean that a component unmounts in React? Does it disappear after it's unmounted?

Viewed 74

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.
2 Answers

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.

Related