Created
October 11, 2019 09:56
-
-
Save freddi301/68ba463381008ebab119e591ed67fcee to your computer and use it in GitHub Desktop.
useInterval #react #hook
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
| /** | |
| * This is an implementation of javascript's imperative setInterval API | |
| * combined with React hooks' declarative approach. | |
| * | |
| * It is actually a replica of Dan Abramov's implementation described here: | |
| * https://overreacted.io/making-setinterval-declarative-with-react-hooks/ | |
| */ | |
| import { useEffect, useRef } from "react"; | |
| export function useInterval(callback: any, delay: number | null) { | |
| const savedCallback = useRef<any | null>(null); | |
| // Remember the latest callback. | |
| useEffect(() => { | |
| savedCallback.current = callback; | |
| }, [callback]); | |
| // Set up the interval. | |
| useEffect(() => { | |
| function tick() { | |
| savedCallback.current(); | |
| } | |
| if (delay !== null) { | |
| const id = setInterval(tick, delay); | |
| return () => clearInterval(id); | |
| } | |
| return; | |
| }, [delay]); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment