3 ms·
function Counter() { const [counter, setCounter] = React.useState(0); React.useEffect(() => { const interval = setInterval(() => setCounter(n => n
by foolbiter 7y 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>
);
}
- andrewstuart 7y agoDoes this continuously clearInterval on every render?
- foolbiter 7y agoNope. 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.
- andrewstuart 7y agoI like it. How did I miss this most obvious and simple solution?
- steve_taylor 7y agoI had no idea the setter can take a function instead of a value. It makes perfect sense, because setState has the same feature. TIL.
- acemarke 7y agoFWIW, it's documented in the API reference: https://reactjs.org/docs/hooks-reference.html#functional-updates https://reactjs.org/docs/hooks-reference.html#functional-upd...