'How to debounce mui Autocomplete

I need to debounce onInputChange function

export interface AutocompleteProps<V extends FieldValues> {
  onInputChange: UseAutocompleteProps<UserOrEmail, true, false, false>['onInputChange'];
}
export default function MyAutocomplete<V extends FieldValues>({
  onInputChange
}: AutocompleteProps<V>) {

  return (
    <Controller
      name={name}
      control={control}
      render={({ field: { onChange, value } }) => (
        <Autocomplete<UserOrEmail, true, false, false>

          onInputChange={onInputChange} //here

        />
      )}
    />
  );

I have done it like this(used debounce outside and passing it like a prop) and it works

const [search, setSearch] = useState('');
const searchDelayed = useCallback(
    debounce((newValue: string) => setSearch(newValue), 100),
    []
  );
      //Passing the prop like this
        /*
           onInputChange={(_, newValue) => {
                        searchDelayed(newValue);
                      }}
        */

I want to debounce in MyAutocomplete but I can not call onInputChange in debounce function. If I do not call it then I get an error, and it does not work

const searchsDelayed = useCallback( //does not work
     debounce(() => onInputChange, 100),
    [onInputChange]
  );

Any ideas how it can be done?



Solution 1:[1]

[Answer reviewed to avoid confusion.]

The main issue is here:

debounce(() => onInputChange, 100);

you are debouncing a function that returns onInputChange, it doesn't invoke it, and it would be needed to be called twice. To fix this, just pass onInputChange directly:

debounce(onInputChange, 100);

Anyway, you are trying to use useCallback but you probably would be fine without any optimization anyway, so you could use

const searchDelayed = debounce(onInputChange, 100);

But if you actually need the optimization, in this case you should use useMemo since you need the result of the debounce invocation:

const searchDelayed = useMemo(
    () => debounce(onInputChange, 100),
    [onInputChange]
);

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