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

140
Visualizações
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 Respostas
Responde à pergunta

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 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