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

148
Visualizações
Cleanup usage in useEffect in React need or not need?

In the below usage for the useEffect hook, I am detecting the window width, then if the window is a certain width the function sets the state, but would I need to cleanup the useEffect in this case or would it need no cleanup? I know in the context of an API you could unsubscribe to the API in the return, So the return will run when the component un mounts

Is it correct in setting the windowWidth again or is it better to remove the return from the useEffect hook totally?

const [windowWidth, setWindowWidth] = React.useState<number>(0);
const [column, setColumn] = React.useState<number>(10);

const calcWindow = React.useCallback(() => {
  if (windowWidth < 768) {
    setColumn(() => 5);
  } else {
    setColumn(() => 10);
  }
}, [windowWidth]);

React.useEffect(() => {
  setWindowWidth(window.innerWidth);
  calcWindow();
  return () => {
    setWindowWidth(window.innerWidth); // is this needed or is this correct?
  };
}, [calcWindow, windowWidth]);
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

The returned function here is unnecessary. When the component is about to unmount, you shouldn't be setting the state since that state is just going to go away. During a re-render, the cleanup function will run and set window width, but the value will be overridden in the effect immediately from the setWindowWidth(window.innerWidth); call.

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