mirror of
https://github.com/Sendouc/sendou.ink.git
synced 2026-06-23 21:22:04 -05:00
20 lines
498 B
TypeScript
20 lines
498 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.
|
|
*/
|
|
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]);
|
|
}
|