hooks
useLoading

useLoading

A custom hook that provides functionalities for managing loading state.

Add hook

Create a file use-loading.ts and copy & paste the code from useLoading.

Hook

 
import { useEffect, useState } from 'react';
 
export const useLoading = <T>(state?: boolean, data?: T) => {
    const [loading, setLoading] = useState(state || false);
 
    const startLoading = () => {
        setLoading(true);
    };
 
    const startLoadingAfter = (timeout: number) => {
        setTimeout(() => {
            setLoading(true);
        }, timeout);
    };
 
    const stopLoading = () => {
        setLoading(false);
    };
 
    const stopLoadingAfter = (timeout: number) => {
        setTimeout(() => {
            setLoading(false);
        }, timeout);
    };
 
    useEffect(() => {
        if (data) {
            setLoading(false);
        }
    }, [data]);
 
    return {
        loading,
        startLoading,
        stopLoading,
        startLoadingAfter,
        stopLoadingAfter,
    };
};
 

Usage

 
import React, { useEffect } from 'react';
import { useLoading } from './hooks/use-loading';
 
function App() {
    const { loading, startLoading, stopLoadingAfter } = useLoading()
 
    useEffect(() => {
        if (loading) {
            stopLoadingAfter(5000)
        }
    }, [loading])
 
    return (
        <>
            <button onClick={() => startLoading()}>Load</button>
            {loading && <p>Loading ....</p>}
        </>
    )
}
 
export default App;
 

API

Parameters

NameTypeDescription
stateboolean (optional)Initial loading state. Default is false.
dataT (optional)Data used to automatically stop loading.

Returns

NameTypeDescription
loadingbooleanIndicates whether the component is in a loading state.
startLoading() => voidFunction to start loading immediately.
startLoadingAfter(timeout: number) => voidFunction to start loading after a specified timeout.
stopLoading() => voidFunction to stop loading immediately.
stopLoadingAfter(timeout: number) => voidFunction to stop loading after a specified timeout.

Contributors

Avatar 1