How can i fix this? I see question like this where people said that useMemo can help. But this is not about like that situation and useMemo fix doesn’t work and create just more bugs.
JavaScript
x
23
23
1
export const Search: React.FC = () => {
2
const dispatch = useDispatch();
3
const [value, setValue] = React.useState<string>('');
4
const inputRef = React.useRef<HTMLInputElement>(null);
5
6
const onClickClear = () => {
7
dispatch(setSearchValue(''));
8
setValue('');
9
inputRef.current?.focus();
10
};
11
12
const updateSearchValue = React.useCallback(
13
debounce((str: string) => {
14
dispatch(setSearchValue(str));
15
}, 150),
16
[],
17
);
18
19
const onChangeInput = (event: React.ChangeEvent<HTMLInputElement>) => {
20
setValue(event.target.value);
21
updateSearchValue(event.target.value);
22
};
23
Advertisement
Answer
can you try this instead? useCallback
takes two params.. an inline function, and a dependency array.
JavaScript
1
11
11
1
const updateSearchValue = React.useCallback((str: string) => {
2
debounce(() => {
3
dispatch(setSearchValue(str));
4
}, 150);
5
}, [dispatch]);
6
7
const onChangeInput = (event: React.ChangeEvent<HTMLInputElement>) => {
8
setValue(event.target.value);
9
updateSearchValue(event.target.value);
10
};
11