Created
May 19, 2022 19:11
-
-
Save JacobJaffe/6d55b594cc250b0a96a115504ef52a1f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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