Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lancegliser/54139335cd824c2b67a2526af5d6bbad to your computer and use it in GitHub Desktop.
Save lancegliser/54139335cd824c2b67a2526af5d6bbad to your computer and use it in GitHub Desktop.
Provides a lodash debounced based implementation of an onChange handler to update state with full Typescript support
import React, {
useState,
useEffect,
ChangeEvent,
useMemo,
ChangeEventHandler,
} from "react";
import { TextField } from "@material-ui/core";
import { debounce } from "lodash";
const SampleComponent: React.FunctionComponent = () => {
const [searchQuery, setSearchQuery] = useState<string | undefined>();
// Create a cached debounce function for change handling
const onSearchChange = useMemo(
() =>
debounce<ChangeEventHandler<HTMLTextAreaElement | HTMLInputElement>>(
(event: ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => {
setSearchQuery(event.target.value);
},
250
),
[setSearchQuery]
);
// Stop the invocation of the debounced function after unmounting
useEffect(() => {
// Note that this is a clean up effect, so its logic must be in a returned function.
return () => {
onSearchChange?.cancel();
};
}, [onSearchChange]);
return (
<TextField
autoFocus
placeholder="Search"
type={"search"}
onChange={onSearchChange}
value={searchQuery}
/>
);
};
export default SampleComponent;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment