Created
March 3, 2022 09:42
-
-
Save toshvelaga/9f34ac50e9fd851d75bf3ea2a0bfe406 to your computer and use it in GitHub Desktop.
custom react hook for polling
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
| import React, { useEffect, useRef } from 'react' | |
| // https://overreacted.io/making-setinterval-declarative-with-react-hooks/ | |
| 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