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
Name | Type | Description |
---|---|---|
state | boolean (optional) | Initial loading state. Default is false . |
data | T (optional) | Data used to automatically stop loading. |
Returns
Name | Type | Description |
---|---|---|
loading | boolean | Indicates whether the component is in a loading state. |
startLoading | () => void | Function to start loading immediately. |
startLoadingAfter | (timeout: number) => void | Function to start loading after a specified timeout. |
stopLoading | () => void | Function to stop loading immediately. |
stopLoadingAfter | (timeout: number) => void | Function to stop loading after a specified timeout. |