Skip to content

Instantly share code, notes, and snippets.

@agrcrobles
Created April 17, 2020 13:53
Show Gist options
  • Save agrcrobles/c7db52372c5d232c5046600cb81cee82 to your computer and use it in GitHub Desktop.
Save agrcrobles/c7db52372c5d232c5046600cb81cee82 to your computer and use it in GitHub Desktop.
Simple Debounce Hook
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;
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