Created
August 7, 2019 23:51
-
-
Save andycarrell/687de18b3a2ec202253e757c5d3bbec2 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 { useEffect, useState } from "react"; | |
function useDebounce(value, delay) { | |
const [debouncedValue, setDebouncedValue] = useState(value); | |
useEffect(() => { | |
const handler = setTimeout(() => { | |
setDebouncedValue(value); | |
}, delay); | |
return () => { | |
clearTimeout(handler); | |
}; | |
}, [value, delay]); | |
return debouncedValue; | |
}; | |
function useDebouncedState(initialState, interval) { | |
const [value, setValue] = useState(initialState); | |
const debouncedValue = useDebounce(value, interval); | |
return [value, setValue, debouncedValue]; | |
} | |
function useDebouncedEffect(value, interval, effect) { | |
const debouncedValue = useDebounce(value, interval); | |
useEffect(() => effect(debouncedValue), [debouncedValue, effect]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment