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

141
Vistas
How to use Clean up function with Async function in UseEffect?

I went through one simple use of the Clean up function. On change of Input text value, we get an alert of the value we have in the text box.

I have code like this

import React, { useState, useEffect } from "react";

function App() {
  const [value, setValue] = useState("");

  //Waits for a period of time then resolves
  function timeout(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  const myAlert =async () =>{
    await timeout(1000);
    alert(`A name was changed: ${value}`);
  }

  useEffect(() => {
    let isCancelled = false;

    const handleChange = async () => {
      if (!isCancelled) {
      await myAlert();
      }
    };

    handleChange();

    return () => {
      isCancelled = true;
    };
  }, [value]);

  return (
    <div className="App">
      <div>
        <form>
          <label>
            Name:
            <input
              type="text"
              value={value}
              onChange={(event) => setValue(event.target.value)}
            />
          </label>
          <input type="submit" value="Submit" />
        </form>
      </div>
    </div>
  );
}

export default App;


Here we are calling myAlert in useEffect. SO, how we can use the Cleanup function with this type of case, where we are not changing the state in useeffect but we call an async function in use effect where we change the state.

codesandbox Link is here : https://codesandbox.io/s/strange-greider-7k1svi?file=/src/App.js

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I'm not sure why do you try to use the cleanup function. In a normal case, you have to set a state in some condition. Effects are controlled via their dependencies, not by the lifecycle of the component that uses them.

Anytime dependencies of an effect change, useEffect will cleanup the previous effect and run the new effect.

import React, { useState, useEffect } from "react";

function App() {
  const [value, setValue] = useState("");
  const [isCancelled, setsCancelled] = useState(false);

  //Waits for a period of time then resolves
  function timeout(ms) {
    return new Promise((resolve) => setTimeout(resolve, ms));
  }

  const myAlert = async () => {
    await timeout(1000);
    alert(`A name was changed: ${value}`);
  };

  useEffect(() => {
    const handleChange = async () => {
      if (isCancelled) {
        setsCancelled(true)
        await myAlert();
      }
    };

    handleChange();

  }, [value]);

  return (
    <div className="App">
      <div>
        <form>
          <label>
            Name:
            <input
              type="text"
              value={value}
              onChange={(event) => setValue(event.target.value)}
            />
          </label>
          <input type="submit" value="Submit" />
        </form>
      </div>
    </div>
  );
}

export default App;
about 4 years ago · Santiago Trujillo 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