UNPKG

@ducor/hooks

Version:

A collection of useful React hooks for building modern web applications. Includes hooks for clipboard operations, window events, intervals, timeouts, and more.

31 lines (30 loc) 863 B
import { useCallback, useMemo, useRef } from "react"; import useBoolean from "../use-boolean"; import useUnmountEffect from "../use-unmount-effect"; /** * `useProcessing` is a custom hook for handling processing states. * * @see Docs https://ui.ducor.net/hooks/use-processing */ export const useProcessing = (init) => { const [isLoading, { off, on }] = useBoolean(init); const countRef = useRef(0); const start = useCallback(() => { countRef.current += 1; on(); }, [on]); const finish = useCallback(() => { countRef.current -= 1; if (countRef.current <= 0) off(); }, [off]); useUnmountEffect(() => { countRef.current = 0; }); const controls = useMemo(() => ({ finish, isLoading, start, }), [finish, isLoading, start]); return controls; };