Skip to content

Instantly share code, notes, and snippets.

@rsturim
Last active January 5, 2022 22:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsturim/fe518e5f94a198199c5b225c4c84fae2 to your computer and use it in GitHub Desktop.
Save rsturim/fe518e5f94a198199c5b225c4c84fae2 to your computer and use it in GitHub Desktop.
import { useMemo, useState, useEffect } from "react";
import { debounce } from "lodash";
export default function Input() {
const [query, setQuery] = useState("");
const changeHandler = (event) => {
setQuery(event.target.value);
};
const debouncedChangeHandler = useMemo(
() => debounce(changeHandler, 300),
[]
);
// Stop the invocation of the debounced function
// after unmounting
useEffect(() => {
return () => {
debouncedChangeHandler.cancel();
};
}, [debouncedChangeHandler]);
return (
<>
<input
onChange={debouncedChangeHandler}
placeholder="Type a query..."
name="inputExample"
/>
<div>{query}</div>
</>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment