2dbi

Design an Autocomplete Component

viaLeetCode

Problem Design and implement an autocomplete/typeahead component: as the user types, fetch and render ranked suggestions, navigable by keyboard.

Requirements

  • Debounced fetch-as-you-type (~300 ms) with a minimum query length; suggestion list with mouse + full keyboard support (arrows, Enter, Escape); loading/empty/error states; select → fill input and close.

Core design

  • Structure: controlled <input> + suggestion listbox; state = {query, suggestions, isOpen, highlightedIndex, status}; a useAutocomplete hook isolating logic from rendering; parent gets onSelect callback.
  • Debounce in an effect (or useDeferredValue) so renders stay cheap; cache query → results (LRU-ish map) to skip repeat fetches; prefix-serving from cache while revalidating.
  • RACE CONDITIONS — the marquee edge case: out-of-order responses (slow "ca" resolving after fast "cat") must not clobber newer results; fix with AbortController on each new keystroke or a request-sequence/stale-closure guard — walk this explicitly.

Discussion points

  • Accessibility: ARIA combobox pattern (role=combobox, aria-expanded, aria-activedescendant, listbox/option roles) — a strong differentiator.
  • Performance: virtualize long lists, memoize row rendering, highlight-matching without regex-injection bugs.
  • Edge cases: empty results messaging, blur-vs-click ordering (mousedown before blur), IME composition, rapid clear, min-chars gating; server-side ranking vs client filtering.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account