Skip to content

Instantly share code, notes, and snippets.

@codemile
Created June 29, 2021 14:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save codemile/04cf5c6c015b19998c8609a01cf999ce to your computer and use it in GitHub Desktop.
Save codemile/04cf5c6c015b19998c8609a01cf999ce to your computer and use it in GitHub Desktop.
Hook that debounces values by discarding inputs that take less than the specified milliseconds between changes.
import {useEffect, useState} from 'react';
export const useDebounce = <TType extends any>(next: TType, ms: number) => {
const [value, setValue] = useState(next);
useEffect(() => {
const id = setTimeout(() => setValue(next), ms);
return () => clearTimeout(id);
}, [next, ms]);
return value;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment