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

127
Visualizações
why React not logging the error when setting state on unmounted component when returning cleanup function

When setting state after a component was unmounted, React should log the following error:

Warning: Can't perform a React state update on an unmounted component.
This is a no-op, but it indicates a memory leak in your application.
To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.

However, If I'm returning an empty function as the cleanup function it would not log the error.

the code:

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

function Comp() {
  const [state, setState] = useState("nothing");

  useEffect(() => {
    setState("loading");

    sleep(1000).then(() => {
      console.log("setting state");
      setState("finished");
    });

    // When the below return exists it does not log the error
    return () => {};
  }, []);

  return <span>{state}</span>;
}

export default function App() {
  const [show, setShow] = useState(true);

  useEffect(() => {
    sleep(500).then(() => setShow(false));
  }, []);

  return (
    <div className="App">
      <h1>
        <button onClick={() => setShow((v) => !v)}>Show</button>
        {show && <Comp />}
      </h1>
    </div>
  );
}

Sandbox link

about 4 years ago · Juan Pablo Isaza
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