Hacker News new | ask | show | jobs
by foolbiter 2379 days ago

  function Counter() {
    const [counter, setCounter] = React.useState(0);
    React.useEffect(() => {
      const interval = setInterval(() => setCounter(n => n + 1), 100);
      return () => clearInterval(interval);
    }, [])

    return (
      <div>{counter}</div>
    );
  }
2 comments

I had no idea the setter can take a function instead of a value. It makes perfect sense, because setState has the same feature. TIL.
FWIW, it's documented in the API reference:

https://reactjs.org/docs/hooks-reference.html#functional-upd...

Does this continuously clearInterval on every render?
Nope. Since the dep array is empty, the effect only runs once after the first render, & the cleanup function returned from the effect only runs on unmount.
I like it. How did I miss this most obvious and simple solution?