Last active
July 13, 2019 14:22
-
-
Save EduVencovsky/466eae6c71c7021a86c3bd5afa6bfcc4 to your computer and use it in GitHub Desktop.
React Hook for using setInterval
This file contains hidden or 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
| // https://overreacted.io/making-setinterval-declarative-with-react-hooks/ | |
| import { useEffect, useRef } from 'react' | |
| function useInterval(callback, delay) { | |
| const savedCallback = useRef() | |
| // Remember the latest callback. | |
| useEffect(() => { | |
| savedCallback.current = callback | |
| }, [callback]) | |
| // Set up the interval. | |
| useEffect(() => { | |
| function tick() { | |
| savedCallback.current() | |
| } | |
| if (delay !== null) { | |
| let id = setInterval(tick, delay) | |
| return () => clearInterval(id) | |
| } | |
| }, [delay]) | |
| } | |
| export default useInterval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment