Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

147
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda