This question is posted as self-answered; as encouraged and described here:
[...] document it in public so others (including yourself) can find it later
This is react-query specific. How can the various options of the useQuery hook best be configured to support an input suggestions functionality (also known as autocomplete and typeahead)?
Does useQuery support:
- debouncing of the input value?
- only sending requests if the input value has at least 3 characters?
- caching responses for previous input values as long as the current user interaction with the text field is not over?
A naïve implementation would deal with all this in userspace (i.e. not using the library, instead implementing it all in custom code):
// [x] debouncing
// [x] at least 3 characters
// [-] caching
const [value, setValue] = useState('');
const [search, setSearch] = useState('');
const { data } = useQuery([search], () => api.getSuggestions(search));
useEffect(() =>
{
if (value.length > 2)
{
const id = setTimeout(() => setSearch(value), 500);
return () => clearTimeout(id);
}
},
[value]);