Created
October 11, 2019 10:01
-
-
Save freddi301/9183575ec36033552095723ce722b723 to your computer and use it in GitHub Desktop.
useScheduledEffect #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
import { useEffect, useRef } from "react"; | |
type TimeoutCallback = (timestamp: number) => void; | |
export function useScheduledEffect( | |
callback: TimeoutCallback, | |
timestamp: number | null, | |
) { | |
const savedCallback = useRef<TimeoutCallback | null>(callback); | |
useEffect(() => { | |
savedCallback.current = callback; | |
}, [callback]); | |
useEffect(() => { | |
if (timestamp == null) { | |
return; | |
} | |
const timeout = Math.max(0, timestamp - Date.now()); | |
const id = setTimeout(() => { | |
if (savedCallback.current != null) { | |
savedCallback.current(Date.now()); | |
} | |
}, timeout); | |
return () => clearTimeout(id); | |
}, [timestamp]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment