2022-11-21 17:33:08 +00:00
|
|
|
import _ from 'lodash';
|
2023-02-22 20:13:33 +00:00
|
|
|
import { useState, useRef, useCallback, useEffect } from 'react';
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2023-02-22 20:13:33 +00:00
|
|
|
export function useDebounce(value: string, onChange: (value: string) => void) {
|
|
|
|
const [debouncedValue, setDebouncedValue] = useState(value);
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2022-11-21 17:33:08 +00:00
|
|
|
const onChangeDebounces = useRef(_.debounce(onChange, 300));
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2023-02-13 02:06:14 +00:00
|
|
|
const handleChange = useCallback(
|
|
|
|
(value: string) => {
|
2023-02-22 20:13:33 +00:00
|
|
|
setDebouncedValue(value);
|
2023-02-13 02:06:14 +00:00
|
|
|
onChangeDebounces.current(value);
|
|
|
|
},
|
2023-02-22 20:13:33 +00:00
|
|
|
[onChangeDebounces, setDebouncedValue]
|
2023-02-13 02:06:14 +00:00
|
|
|
);
|
2022-01-04 12:16:09 +00:00
|
|
|
|
2023-02-22 20:13:33 +00:00
|
|
|
useEffect(() => {
|
|
|
|
setDebouncedValue(value);
|
|
|
|
}, [value]);
|
|
|
|
|
|
|
|
return [debouncedValue, handleChange] as const;
|
2022-01-04 12:16:09 +00:00
|
|
|
}
|