Created
February 26, 2021 13:17
-
-
Save NemanjaMandic/b2b7b6c7594084b5c5684ed601c078c7 to your computer and use it in GitHub Desktop.
React debounce hook
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, useEffect } 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; | |
} | |
export default useDebounce; | |
// Usage | |
const [searchTerm, setSearchTerm] = useState(""); | |
const debouncedSearchTerm = useDebounce(searchTerm, 500); | |
useEffect(() => { | |
if (debouncedSearchTerm) { | |
searchNews(debouncedSearchTerm); | |
} | |
}, [debouncedSearchTerm]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment