tbleckert / react-select-search

⚡️ Lightweight select component for React
https://react-select-search.com
MIT License
676 stars 147 forks source link

[feature] Add debounce mode to skip requests on api every typing when use getOptions #105

Closed etc-tiago closed 3 years ago

etc-tiago commented 4 years ago

Since getOptions can be an entry to communicate with the api and search for research data, debounce can be useful to avoid unnecessary requirements on each key press. Here is an example that can be used.

import { useState, useEffect } from 'react';

// Set change when deplay finish, if another event its set, the delay restart
export const debounce = (value: string, delay: number) => {
  const [state, setState] = useState(value);

  useEffect(() => {
    const handler = setTimeout(() => setState(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);

  return state;
};
tbleckert commented 4 years ago

@etc-tiago Hm true. In my own use cases I've had the debouncing on my end, but maybe it makes more sense to have it built in. Maybe with the delay time configurable.