Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Created January 27, 2021 18:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelbr/2e5848dd731cd1ed4aeeabb50c8a68a2 to your computer and use it in GitHub Desktop.
Save mikaelbr/2e5848dd731cd1ed4aeeabb50c8a68a2 to your computer and use it in GitHub Desktop.
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