Skip to content

Instantly share code, notes, and snippets.

@madflanderz
Last active February 24, 2021 11:31
Show Gist options
  • Save madflanderz/c296e520e7ec60f9867d89308c51a3e7 to your computer and use it in GitHub Desktop.
Save madflanderz/c296e520e7ec60f9867d89308c51a3e7 to your computer and use it in GitHub Desktop.
useDebouncedState hook
import { useState, Dispatch, SetStateAction, useEffect } from "react"
/**
* useDebouncedState can be used to debounce value updates for given delay.
*
* Example Usecase: You have a search field and want to load sugestions.
* Api should only be called when last user interaction is minimum 300ms ago.
*
* Usage: debouncedValue is updated after 500 ms
* const [value, debouncedValue, setValue] = useDebouncedState("", 500)
*/
const useDebouncedState = <T>(
initialValue: T,
delay = 300
): [T, T, Dispatch<SetStateAction<T>>] => {
const [value, setValue] = useState(initialValue)
const [debouncedValue, setDebouncedValue] = useState(initialValue)
useEffect(() => {
setValue(initialValue)
setDebouncedValue(initialValue)
}, [initialValue])
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(handler)
}
}, [delay, value])
return [value, debouncedValue, setValue]
}
export default useDebouncedState
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment