See https://stackoverflow.com/questions/52561133/how-to-perform-debounce-on-onchange-react-event
Created
April 17, 2020 13:53
-
-
Save agrcrobles/c7db52372c5d232c5046600cb81cee82 to your computer and use it in GitHub Desktop.
Simple Debounce Hook
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 * as React from "react"; | |
import useDebounceCallback from "../utils/useDebounceCallback"; | |
const SearchInput = (props) => { | |
const [searchValue, setSearchValue] = React.useState(""); | |
const handleDispatch = useDebounceCallback(() => { | |
console.log("dispatch criteria: ${searchValue}"); | |
}, 1000); | |
const handleSearch = (e) => { | |
e.preventDefault(); | |
setSearchValue(e.target.value); | |
handleDispatch(); | |
}; | |
return ( | |
<input | |
type="text" | |
value={searchValue} | |
onChange={handleSearch} | |
/> | |
); | |
}; | |
export default SearchInput; |
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, useRef } from "react"; | |
export default function useDebounceCallback(callback, wait) { | |
// track args & timeout handle between calls | |
const argsRef = useRef(); | |
const timeout = useRef(); | |
function cleanup() { | |
if (timeout.current) { | |
clearTimeout(timeout.current); | |
} | |
} | |
// make sure our timeout gets cleared if | |
// our consuming component gets unmounted | |
useEffect(() => cleanup, []); | |
return function debouncedCallback(...args) { | |
// capture latest args | |
argsRef.current = args; | |
// clear debounce timer | |
cleanup(); | |
// start waiting again | |
timeout.current = setTimeout(() => { | |
if (argsRef.current) { | |
callback(...argsRef.current); | |
} | |
}, wait); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment