Uploaded an imagecan you make a good solution
- User
Uploaded an imagecan you make a good solution
- Assistant
Here’s a drop-in hook that follows the two rules listed:
ignore ≤ 150 ms: totrueand back tofalseinside the “ignore” window, the hookneverreturnstrue.
atLeast ≥ 300 ms:once the hook does returntrue, it staystruefor at least that long—even ifpendingflips back tofalsesooner.
ignore ≤ 150 ms: totrueand back tofalseinside the “ignore” window, the hookneverreturnstrue.
atLeast ≥ 300 ms:once the hook does returntrue, it staystruefor at least that long—even ifpendingflips back tofalsesooner.
────────────────────────────────────────────────────────────────────
tsxCopy codeimport { useEffect, useRef, useState } from "react";
type Options = { /** how long to ignore micro-blips (ms) / ignore?: number; /* minimum time the flag must stay true once shown */ atLeast?: number; };
/**
- Debounces a
pendingflag so that short spikes are hidden - and genuine “loading” states show for a minimum duration.
- @example
- const { pending } = useFormStatus();
- const noFlicker = usePendingDelay(pending, { ignore: 150, atLeast: 300 }); */ export function usePendingDelay( pending: boolean, { ignore = 150, atLeast = 300 }: Options = {} ): boolean { const [visible, setVisible] = useState(false);
// hold timer ids & the current pending value across renders const ignoreTimer = useRef<ReturnType | null>(null); const minVisibleTimer = useRef<ReturnType | null>(null); const latestPending = useRef(pending);
latestPending.current = pending; // keep up-to-date for timer callbacks
useEffect(() => { // ⚙️ START of a request --------------------------------------------- if (pending) { // Already waiting? nothing to do if (visible) return;
code - Debounces a