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

113
Vistas
How to use Cleanup in useEffect

I have the below code, where it pull all data from server as API

  export const apiExpenses = () => {

    //Get All Expenses, Realtime
    const { data: tableDataExpenses, error, mutate } = useSWR('/api/expenses/datatable', () =>
      axios
          .get('/api/expenses/datatable')
          .then(res => res.data),        
    )

    return {
        tableDataExpenses,
      }

  }

And using the output of that API in another component with useEffect

const { tableDataExpenses } = apiExpenses();
const [expenses, setExpenses] = useState([]);

useEffect(() => {
    setExpenses(tableDataExpenses.data);

    return () => {
      setExpenses([]);
    };
  }, [tableDataExpenses]);

But I am ending in below errors,

 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.

And because of this, I can't get the value of tableDataExpenses

If I remove setExpenses from useEffect there are no errors and again if I write setExpenses it loads data.

But again in the next render, it fails with error.

So How can I prevent this error with the cleanup function?

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