Created
January 6, 2022 19:20
-
-
Save davemecha/8aeec4f699823517b74176bbf76abba2 to your computer and use it in GitHub Desktop.
A debounced Material UI TextField component
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 { TextField, TextFieldProps } from '@material-ui/core'; | |
import { ChangeEvent, memo, useCallback, useEffect, useRef, useState } from 'react'; | |
function DebouncedTextField({ value, onChange, timeout = 1000, ...props }: TextFieldProps & { timeout?: number }) { | |
const timeoutHandlerRef = useRef<ReturnType<typeof setTimeout>>(); | |
const [currentValue, setCurrentValue] = useState(value); | |
const handleChange = useCallback((event: ChangeEvent<HTMLTextAreaElement | HTMLInputElement>) => { | |
const value = event.target.value; | |
setCurrentValue(value); | |
if (!onChange) return; | |
if (timeoutHandlerRef.current) clearTimeout(timeoutHandlerRef.current); | |
timeoutHandlerRef.current = setTimeout(() => onChange(event), timeout); | |
}, [onChange, timeout]); | |
useEffect(() => { | |
setCurrentValue(value); | |
// clear possible timeout on unmount / input value change | |
return () => timeoutHandlerRef.current && clearTimeout(timeoutHandlerRef.current); | |
}, [value]); | |
return (<TextField value={ currentValue } onChange={ handleChange } { ...props } />); | |
} | |
export default memo(DebouncedTextField); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment