score:3

Accepted answer

it's best to run this kind of effect in a useeffect hook. that way, you can run the effect whenever counter is updated and provide a mechanism to cancel an existing timeout.

when the timeout hits 1 second, the counter stateful variable will be incremented. since counter is specified in the useeffect dependency array, the effect will run again, queuing up another timeout.

we return a cleanup function from our usereffect hook. this is important because, if our counter is changed by some other mechanism (e.g., the reset button), we'll want to cancel the in-progress timeout to start over!

import react, { usestate, useeffect } from "react";

const app = (props) => {
  const [counter, setcounter] = usestate(0)

  useeffect(() => {
    const timeout = settimeout(
      () => setcounter(counter + 1),
      1000  
    )
    return () => {
      cleartimeout(timeout);
    }
  }, [counter])

  return (
    <div>
      <h1>{counter}</h1>
      <button onclick={()=>setcounter(0)}>reset</button>
    </div>
  )
}

Related Query

More Query from same tag