Created
August 29, 2021 13:51
-
-
Save yeonwooz/46717c9c18360d0f30d54a22b172f683 to your computer and use it in GitHub Desktop.
useInterval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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