Skip to content

Instantly share code, notes, and snippets.

@tjenkinson
Last active June 9, 2022 08:02
Show Gist options
  • Save tjenkinson/01f58b13f9f10d43442e6b073b0dfc3f to your computer and use it in GitHub Desktop.
Save tjenkinson/01f58b13f9f10d43442e6b073b0dfc3f to your computer and use it in GitHub Desktop.
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