Created
April 27, 2024 20:08
-
-
Save alexdemers/14b81f4fbdf29aaa4a678e8e5e3d82fb to your computer and use it in GitHub Desktop.
useDebouncedState
This file contains 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 { useEffect, useState } from 'react'; | |
export const useDebouncedState = <T>(initialValue: T, delay: number) => { | |
const [value, setValue] = useState(initialValue); | |
const [debouncedValue, setDebouncedValue] = useState(value); | |
useEffect(() => { | |
const handler = setTimeout(() => { | |
setDebouncedValue(value); | |
}, delay); | |
return () => { | |
clearTimeout(handler); | |
}; | |
}, [value, delay]); | |
return [debouncedValue, value, setValue] as const; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment