Skip to content

Instantly share code, notes, and snippets.

@davemecha
Created January 6, 2022 19:20
Show Gist options
  • Save davemecha/8aeec4f699823517b74176bbf76abba2 to your computer and use it in GitHub Desktop.
Save davemecha/8aeec4f699823517b74176bbf76abba2 to your computer and use it in GitHub Desktop.
A debounced Material UI TextField component
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