Last active
August 21, 2020 15:28
-
-
Save ever-dev/eb8481ac9845db01d09bec222ef73b30 to your computer and use it in GitHub Desktop.
useTimer Custom Hook
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 { useState, useEffect } from "react"; | |
export const useTimer = (delay: number) => { | |
const [clock, setClock] = useState(false); | |
useEffect( | |
() => { | |
// toggle clock | |
const handler = setInterval(() => { | |
setClock((v) => !v); | |
}, delay); | |
return () => { | |
clearInterval(handler); | |
}; | |
}, | |
[delay] | |
); | |
return clock; | |
}; | |
/* Usage: | |
import { useTimer } from './useTimer'; | |
... | |
const timer = useTimer(delay); | |
useEffect(() => {...}, [timer]); | |
... | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment