Skip to content

Instantly share code, notes, and snippets.

@julenwang
Last active October 22, 2021 09:37
Show Gist options
  • Save julenwang/1cffff7c0a881d581573589a0d4ad98f to your computer and use it in GitHub Desktop.
Save julenwang/1cffff7c0a881d581573589a0d4ad98f to your computer and use it in GitHub Desktop.
useDelayLoading
import { useEffect, useRef, useState } from 'react';
const useDelayLoading = (isLoading: boolean, delay = 1500): boolean => {
const [loading, setLoading] = useState(false);
const timerRef = useRef<number>();
useEffect(() => {
const timer = timerRef.current;
if (isLoading) {
timerRef.current = setTimeout(() => {
setLoading(true);
}, delay) as unknown as number;
} else {
if (timer !== null) {
clearTimeout(timer);
}
setLoading(false);
}
return () => {
if (timer !== null) {
clearTimeout(timer);
}
};
}, [delay, isLoading]);
return loading;
};
export default useDelayLoading;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment