Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

255
Visualizações
What exactly does it mean that a component unmounts in React? Does it disappear after it's unmounted?

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.
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

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".

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda