Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!