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.
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.
Also asked at СБЕР
- Have you worked with useLayoutEffect and how does it differ from useEffect?
- [name] asked: why did you decide to change your job?
- What is Event Loop in JavaScript?
- What is Virtual DOM and how does it work in React?
- Please tell us about your experience: what tasks do you solve, what is your area of responsibility, what technologies have you worked with, and how are the team processes organized?
Similar questions
- Implement a useDebounce hook that accepts a callback and a delay, cancels the previous timer when called again, invokes the latest version of the callback with the passed arguments, and clears the timer when the component unmounts.
- Implement a `debounce` function.
- Extend `debounce`: add the ability to cancel a delayed invocation and to invoke the supplied callback immediately.
- Type the written function in TypeScript using generics so that it works not only with numbers but also with other types.
- Add TypeScript types to a function called mutateProp that takes an object, one of its keys, and a new property value; the value’s type must match the type of the selected property of the object.