Real World Example

Real World: Search suggestions and infinite scroll

Amazon's search box asks for suggestions only after you pause typing (debounce). Instagram checks scroll position at most every 200 ms to load the next posts (throttle).

// debounce: search suggestions
const debouncedQuery = useDebounce(query, 400);
useEffect(() => {
  if (debouncedQuery) fetch('/api/suggest?q=' + debouncedQuery).then((r) => r.json()).then(setSuggestions);
}, [debouncedQuery]);

// throttle: load more posts near the bottom
useEffect(() => {
  const onScroll = throttle(() => {
    if (window.innerHeight + window.scrollY > document.body.offsetHeight - 300) loadMore();
  }, 200);
  window.addEventListener('scroll', onScroll);
  return () => window.removeEventListener('scroll', onScroll);
}, []);