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

175
Visualizações
How the returned function is not destroying event listener in useEffect?

I made this custom hook to get window width. It is working but I have a question. I used useEffect to add event listener to window at component mount. But then my friend suggested me to use return function to remove the event listener. How this is working? Shouldn't the returned function destroy the event listener and make it not work? Since this is happing one time on component mount ?

import React from "react";

const useWindowSize = () => {
  const [windowSize, setWindowSize] = React.useState({
    width: window.innerWidth,
    height: window.innerHeight,
  });
  const windowResize = () => {
    setWindowSize({
      width: window.innerWidth,
      height: window.innerHeight,
    });
  };
  React.useEffect(() => {
    window.addEventListener("resize", windowResize);
    return () => {
      window.removeEventListener("resize", windowResize);
    };
  }, []);
  return windowSize;
};

export default useWindowSize;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The returned function inside the useEffect gets executed just before your component gets unmounted. It is not executed on mount.

Without this returned function, every time your component re-renders, if you hadn't that empty array dependency, and when it gets unmounted and mounted, a new EventListener is added in memory (which is bad).

about 4 years ago · Juan Pablo Isaza Relatório

0

This callback in return of useEffect is called on unmount. Which means that eventListener is removed when your component is no longer rendered, or when its "remounted" (key prop was changed). This is important because without removing event listener, there will be several same eventListeners hooked at the same time.

about 4 years ago · Juan Pablo Isaza Relatório

0

shouldn't return function destroy event listener and make it not work? since this is happing one time on component mount ?

The return function will be executed in your case when the component using the hook unmounts (because of empty array as dependencies). So at that time it makes sense to unregister the listener I suppose. More reading.

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