Created
November 4, 2021 14:50
-
-
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
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 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