Skip to content

Instantly share code, notes, and snippets.

@sstur
Created January 24, 2020 20:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sstur/f177248a8ab3a7565328286eda7c4420 to your computer and use it in GitHub Desktop.
Save sstur/f177248a8ab3a7565328286eda7c4420 to your computer and use it in GitHub Desktop.
import { useCallback, useState, useRef } from 'react';
export function useDebounce<T>(initialValue: T, ms: number) {
let [value, setValue] = useState(initialValue);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let timeout = useRef<any>();
let debouncedSetter = useCallback(
(newValue: T) => {
clearTimeout(timeout.current);
timeout.current = setTimeout(() => {
setValue(newValue);
}, ms);
},
[ms],
);
return [value, debouncedSetter];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment