Last active
June 9, 2022 08:02
-
-
Save tjenkinson/01f58b13f9f10d43442e6b073b0dfc3f to your computer and use it in GitHub Desktop.
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, useRef, useEffect } from 'react'; | |
export function useDelay(current, delay) { | |
const [toRender, setToRender] = useState(current); | |
const queuedTimer = useRef(null); | |
const latest = useRef(current); | |
useEffect(() => { | |
if (latest.current !== current) { | |
if (!queuedTimer.current) { | |
queuedTimer.current = setTimeout(() => { | |
queuedTimer.current = null; | |
setToRender(latest.current); | |
}, delay); | |
} | |
latest.current = current; | |
} | |
}); | |
useEffect(() => { | |
return () => { | |
if (queuedTimer.current) clearInterval(queuedTimer.current); | |
}; | |
}, []); | |
return { toRender, old: toRender !== current }; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment