sendou.ink/app/hooks/useDebounce.ts
Kalle 4622426c07
Some checks are pending
E2E Tests / e2e (push) Waiting to run
Tests and checks on push / run-checks-and-tests (push) Waiting to run
Updates translation progress / update-translation-progress-issue (push) Waiting to run
Eliminate useEffects (#3273)
2026-08-03 08:53:08 +03:00

24 lines
724 B
TypeScript

import * as React from "react";
/**
* Runs `fn` once `ms` has elapsed without any value in `deps` changing. The
* timer is (re)started on mount and whenever `ms` or a value in `deps` changes.
*
* Uses the latest-ref pattern instead of `useEffectEvent`: effect events don't
* update past the first render inside `React.memo`/`React.forwardRef` wrapped
* components (React 19.2), which would silently break callers.
*/
export function useDebounce(
fn: () => void,
ms = 0,
deps: React.DependencyList = [],
) {
const callback = React.useRef(fn);
callback.current = fn;
React.useEffect(() => {
const timeout = setTimeout(() => callback.current(), ms);
return () => clearTimeout(timeout);
}, [ms, ...deps]);
}