Skip to content

Instantly share code, notes, and snippets.

@yeonwooz
Created August 29, 2021 13:51
Show Gist options
  • Save yeonwooz/46717c9c18360d0f30d54a22b172f683 to your computer and use it in GitHub Desktop.
Save yeonwooz/46717c9c18360d0f30d54a22b172f683 to your computer and use it in GitHub Desktop.
useInterval
function Counter() {
const [count, setCount] = useState(0);
const savedCallback = useRef();
function callback() {
setCount(count + 1);
}
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
function tick() {
savedCallback.current();
}
let id = setInterval(tick, 1000);
return () => clearInterval(id);
}, []);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment