Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Created January 27, 2021 18:14
Show Gist options
  • Select an option

  • Save mikaelbr/2e5848dd731cd1ed4aeeabb50c8a68a2 to your computer and use it in GitHub Desktop.

Select an option

Save mikaelbr/2e5848dd731cd1ed4aeeabb50c8a68a2 to your computer and use it in GitHub Desktop.

Revisions

  1. mikaelbr created this gist Jan 27, 2021.
    34 changes: 34 additions & 0 deletions use-is-loading.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,34 @@
    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];
    }