Skip to content

Instantly share code, notes, and snippets.

@luigircruz
Last active June 17, 2022 03:55
Show Gist options
  • Select an option

  • Save luigircruz/c787fe4a15bf09fc9163c5ebfe1df3d4 to your computer and use it in GitHub Desktop.

Select an option

Save luigircruz/c787fe4a15bf09fc9163c5ebfe1df3d4 to your computer and use it in GitHub Desktop.
import { useState, useEffect } from "react";
export default function useDebounce(value, delay) {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}
// Use the hook on your component
// Example...
import { useState, useEffect } from "react";
import useDebounce from "./utils/useDebounce";
export default function SampleComponent() {
const [val, setVal] = useState("");
const [debounceVal, setDebounceVal] = useState(val);
const debouncedInputValue = useDebounce(val, 1000);
useEffect(() => {
if (debouncedInputValue) {
setDebounceVal(debouncedInputValue);
}
}, [debouncedInputValue]);
const handleChange = ({ currentTarget }) => {
setVal(currentTarget.value);
};
return (
<div className="App">
<div>
<input
type="text"
value={val}
placeholder="Debounced input"
onChange={handleChange}
/>
</div>
<div>Debounced value: {debounceVal}</div>
</div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment