/* eslint-disable @typescript-eslint/no-explicit-any */ import type { DependencyList } from 'react'; import { useCallback, useEffect, useLayoutEffect, useReducer, useRef, useState } from 'react'; type Destructor = () => void; type AsyncEffectCallback = () => void | Destructor | Promise | Promise; const idPool: { [key: string]: number } = {}; export const useUniqId = (key: string) => { return useState(() => { if (!idPool[key]) idPool[key] = 1; return idPool[key]++; })[0]; }; export const useUniqHandlerId = (name: string) => { const id = useUniqId(name); return `${name}_${id}`; }; export const useForceUpdate = () => { const [, updater] = useState(0); return useCallback(() => updater((prev) => prev + 1), []); }; export const useAsyncEffect = (asyncEffect: AsyncEffectCallback, deps?: DependencyList) => { useEffect(createAsyncEffectCallback(asyncEffect), deps); }; export const useAsyncLayoutEffect = (asyncEffect: AsyncEffectCallback, deps?: DependencyList) => { useLayoutEffect(createAsyncEffectCallback(asyncEffect), deps); }; export const useIIFE = (callback: () => T) => { return iife(callback); }; const iife = any>(callback: T): ReturnType => callback(); const createAsyncEffectCallback = (asyncEffect: AsyncEffectCallback) => () => { const destructor = iife(asyncEffect); return () => { if (!destructor) return; // Not `instanceof Promise`: it fails when `global.Promise` is replaced at startup, by an APM agent or a polyfill. if (typeof destructor === 'function') { iife(destructor); } else { iife(async () => { const awaitedDestructor = await destructor; if (typeof awaitedDestructor === 'function') awaitedDestructor(); }); } }; }; export const useIsMountedRef = () => { const isMounted = useRef(true); useEffect(() => { return () => { isMounted.current = false; }; }, []); return isMounted; }; export const useIsFirstMount = () => { const isFirstMount = useRef(true); if (isFirstMount.current) { isFirstMount.current = false; return true; } return isFirstMount.current; }; export const useFreshCallback = (callback: T): T => { const ref = useRef(callback); ref.current = callback; return useCallback(((...args: any[]) => ref.current(...args)) as unknown as T, []); }; export const useDebounceEffect = (action: () => void, delay: number, deps: DependencyList = []) => { const timeoutRef = useRef(undefined); useEffect(() => { timeoutRef.current = setTimeout(async () => { try { await action(); } finally { timeoutRef.current = undefined; } }, delay); return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); timeoutRef.current = undefined; } }; }, [delay, ...deps]); }; export const usePartialState = (initialState: S) => { return useReducer((prev: S, state: Partial) => ({ ...prev, ...state }), initialState); }; export const useRefTracker = (target: T) => { const ref = useRef(target); useLayoutEffect(() => { ref.current = target; }); return ref; };