'Lodash debounce error: Uncaught TypeError: Expected a function

I am trying to use the debounce function to avoid multiple calls when I'm typing and searching something in a table. This is what I have done -

onChange={(_event, searchText) => React.useCallback(debounce(void setSearchText(searchText), _searchDebounceWaitTime), [])}

It gives an error stating Uncaught TypeError: Expected a function What am I doing wrong ? Most solutions I found online have done a similar thing.

Note: I also tried doing -

onChange={(_event, searchText) => React.useCallback(debounce(searchText => setSearchText(searchText), _searchDebounceWaitTime), [])}

but this time I got the following error - Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

Pls help.



Solution 1:[1]

First of all, as the error states, a react hook cannot be in the jsx. It should be like this:

const onChange = React.useCallback((_event, searchText) => setSearchText(searchText), [])

//...
return (
  <Component
    //...
    onChange={onChange}
  />
);

Then, for a debounce, what you are looking for is a memoized function:

const onChange = React.useMemo(() => debounce((_event, searchText) => setSearchText(searchText), _searchDebounceWaitTime), [])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Luís Alves