Skip to content

Instantly share code, notes, and snippets.

@JacobJaffe
Created May 19, 2022 19:11
Show Gist options
  • Save JacobJaffe/6d55b594cc250b0a96a115504ef52a1f to your computer and use it in GitHub Desktop.
Save JacobJaffe/6d55b594cc250b0a96a115504ef52a1f to your computer and use it in GitHub Desktop.
import { useState, useRef, useEffect } from "react";
// For wrapping state that is frequently updated, but used for an api,
// e.g. a text input hooked up to a search query.
export function useDebouncedTrigger<T>(trigger: T): T {
const [debouncedTrigger, setDebouncedTrigger] = useState(trigger);
const _timeout = useRef<NodeJS.Timeout | null>(null);
useEffect(() => {
_timeout.current = setTimeout(() => {
setDebouncedTrigger(trigger);
}, 300);
return () => {
if (_timeout.current) {
clearTimeout(_timeout.current);
}
};
}, [trigger]);
return debouncedTrigger;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment