Skip to content
Middle+4 views

Add TypeScript typing to the useDebounce hook using a generic so that the returned function's type matches the type of the input callback.

Practice

Asked at

AI answer

You can constrain the callback type to functions and infer the argument types with Parameters<T>. Because the call is deferred, the returned function usually has a void return type, even if the callback itself returns a value.

import { useCallback, useEffect, useRef } from 'react';

type AnyFunction = (...args: any[]) => unknown;

function useDebounce<T extends AnyFunction>(
  callback: T,
  delay: number,
): (...args: Parameters<T>) => void {
  const callbackRef = useRef(callback);
  const timerRef = useRef<ReturnType<typeof setTimeout> | undefined>();

  useEffect(() => {
    callbackRef.current = callback;
  }, [callback]);

  useEffect(() => () => clearTimeout(timerRef.current), []);

  return useCallback((...args: Parameters<T>) => {
    clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => callbackRef.current(...args), delay);
  }, [delay]);
}

This way, TypeScript checks the arguments passed to the returned function against the callback's signature. If the debounce needs to preserve the this context, its type and invocation must be adapted accordingly.