Created
September 2, 2020 15:38
-
-
Save simsketch/f3e3c268fb5f7577e78e62b762df428d to your computer and use it in GitHub Desktop.
React useInterval in TypeScript
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
import React, { useState, useEffect, useRef } from 'react'; | |
export function useInterval(callback: () => void, delay: number | null) { | |
const savedCallback = useRef<any>(); | |
// 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]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment