返回 presentation-ai
debounced-input.tsx
根目录 / src / components / ui / debounced-input.tsx
1 import { Input } from "@/components/ui/input";
2 import debounce from "lodash.debounce";
3 import { useEffect, useMemo, useState } from "react";
4
5 export interface DebouncedInputProps extends Omit<
6 React.ComponentProps<typeof Input>,
7 "onChange"
8 > {
9 value: string | number;
10 onChange: (value: string | number) => void;
11 debounceTimeout?: number;
12 }
13
14 export function DebouncedInput({
15 value: initialValue,
16 onChange,
17 debounceTimeout = 500,
18 ...props
19 }: DebouncedInputProps) {
20 const [value, setValue] = useState(initialValue);
21
22 useEffect(() => {
23 setValue(initialValue);
24 }, [initialValue]);
25
26 const debouncedOnChange = useMemo(
27 () => debounce(onChange, debounceTimeout),
28 [onChange, debounceTimeout],
29 );
30
31 // Cleanup debounce on unmount
32 useEffect(() => {
33 return () => {
34 debouncedOnChange.cancel();
35 };
36 }, [debouncedOnChange]);
37
38 return (
39 <Input
40 {...props}
41 value={value}
42 onChange={(e) => {
43 const newValue = e.target.value;
44 setValue(newValue);
45 debouncedOnChange(newValue);
46 }}
47 />
48 );
49 }
50
50 lines Plain Text