Created
October 24, 2025 06:47
-
-
Save librz/dcde72b68733dda55cfd6291a77287cf to your computer and use it in GitHub Desktop.
Input with auto debounce
This file contains hidden or 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 { debounce } from "es-toolkit"; | |
| import { | |
| useCallback, | |
| useRef, | |
| useState, | |
| type ChangeEventHandler, | |
| type InputHTMLAttributes, | |
| } from "react"; | |
| import { useUpdateEffect } from "react-use"; | |
| export type InputProps = InputHTMLAttributes<HTMLInputElement> & { | |
| /** | |
| * if set to true, debounce onChange | |
| * note: input text itself is never debounced, user typing shouldn't have any lag | |
| */ | |
| debounced?: boolean; | |
| debounceMs?: number; | |
| }; | |
| export function Input(props: InputProps) { | |
| const { | |
| value: valueProp, | |
| onChange: onChangeProp, | |
| debounced = false, | |
| debounceMs = 300, | |
| ...inputProps | |
| } = props; | |
| const [internalValue, setInternalValue] = useState(valueProp); | |
| useUpdateEffect(() => { | |
| setInternalValue(valueProp); | |
| }, [valueProp]); | |
| const onChangeDebounced = useCallback( | |
| debounce<ChangeEventHandler<HTMLInputElement>>((e) => { | |
| onChangeProp && onChangeProp(e); | |
| }, debounceMs), | |
| [debounceMs], | |
| ); | |
| return ( | |
| <input | |
| value={internalValue} | |
| onChange={(e) => { | |
| setInternalValue(e.target.value); | |
| if (!onChangeProp) { | |
| return; | |
| } | |
| // intercept onChange, debounce if needed | |
| const onChangeHandler = debounced ? onChangeDebounced : onChangeProp; | |
| onChangeHandler(e); | |
| }} | |
| {...inputProps} | |
| /> | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment