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

192
Views
can't get updated state value inside method

I wanna stop the looping when stopState is true.

The stopState is updated when I click the stop button. but inside the startIncrement method, the stopState is always false.

This is my code:

function App() {
  const [num, setNum] = useState(0)
  const [stop, setStop] = useState(false)

  function Delay(ms) {
    return new Promise((resolve) => {
      setTimeout(resolve, ms);
    });
  }

  async function startIncrement(){
    for(let i=0; i<100; i++){
      console.log(stop) // always false even when i click the stop button
      if(stop) i = 2000;
      setNum(i)
      await Delay(1000)
    }
  }
  
  return (
    <main>
      <p>stop: {stop ? "true" : "false"}</p>
      <p onClick={startIncrement}>{num}</p>
      <button onClick={() => setStop(true)}>stop</button>
    </main>
  );
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Short answer:

In order to stop the previously excuted function, you will have to invoke a `clean up` function.

Detail on how it works:

In react, each render has it's own props and state, and we can explain this in action:
  1. First, you excuted the function startIncrement(), at the time of excution, and at that perticular render phase, the value of stop is false;
  2. Every time the num value changes, the page renders, and it just keep going... (excute below code, you can see console prints "renders!")
  3. Then you click setStop(true) button, and at this particular render, stop === true.

However, these two steps involves two different renders, and each renders' state and everything else (props, effect...), does not affect each other, therefore, your stop value in the function never changes.

Here's an alternative to achieve the same:

export default function App() {
  const [num, setNum] = useState(0)
  const [stop, setStop] = useState(null)
  console.log("renders!")

  useEffect(() => {
    const run = setInterval(() => {
      if(stop === false && num < 100) setNum(num + 1);
    }, 1000);

    return () => clearInterval(run) // clean up function
  }, [num, stop]);
  
  return (
    <main>
      <p>stop: {stop ? "true" : "false"}</p>
      <p>{num}</p>
      <button onClick={() => setStop(false)}>start</button>
      <button onClick={() => setStop(true)}>stop</button>
    </main>
  );
}

The clean up function in useEffect can be seen as a "undo" function.

Sandbox here, you can read more about side effect from this post in Dan Abramov's blog

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