Last active
October 22, 2021 09:37
-
-
Save julenwang/1cffff7c0a881d581573589a0d4ad98f to your computer and use it in GitHub Desktop.
useDelayLoading
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, 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