Created
January 27, 2021 18:14
-
-
Save mikaelbr/2e5848dd731cd1ed4aeeabb50c8a68a2 to your computer and use it in GitHub Desktop.
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, useState} from 'react'; | |
/** | |
* A specialized useState hook for doing isLoading messages. This delays | |
* setting flag as true for `delayTimeInMs`. This is to avoid unnecessary loading indicators. | |
* | |
* @param {boolean} initialState initial flag, true if loading false otherwise. | |
* @param {number} [delayTimeInMs=400] milliseconds to delay before setting flag to true | |
* @returns {[boolean, React.Dispatch<React.SetStateAction<boolean>>]} usual useState return | |
*/ | |
export default function useIsLoading( | |
initialState: boolean, | |
delayTimeInMs: number = 400, | |
): [boolean, React.Dispatch<React.SetStateAction<boolean>>] { | |
const [isLoading, setIsLoading] = useState(initialState); | |
const [isLoadingInternal, setIsLoadingInternal] = useState(initialState); | |
useEffect(() => { | |
if (!isLoadingInternal) { | |
setIsLoading(isLoadingInternal); | |
return; | |
} | |
const timer = setTimeout( | |
() => setIsLoading(isLoadingInternal), | |
delayTimeInMs, | |
); | |
return () => { | |
clearTimeout(timer); | |
}; | |
}, [isLoadingInternal]); | |
return [isLoading, setIsLoadingInternal]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment