Skip to main content
01

Design an autocomplete (typeahead) component

MediumAutocompleteDebounceCachingAccessibility

Design an autocomplete (typeahead) component: as the user types into a search box, a list of suggestions appears below it, and they can pick one with the mouse or the keyboard.

A typical framing: "Design the search box at the top of an e-commerce site. Suggestions come from a backend API. It should feel instant, work with a keyboard and a screen reader, and be reusable by other teams for other data sources."

TL;DR

The component has three parts: an input, a suggestion list (a popup), and a controller that turns keystrokes into requests and results into UI state. The interesting parts are almost all in the controller:

  • Don't call the API on every keystroke: debounce the input (about 200-300 ms) and skip queries shorter than a minimum length.
  • Handle race conditions: responses can arrive out of order, so only render the result for the latest query, and abort stale requests with AbortController.
  • Cache results per query string in memory (an LRU map), so backspacing is instant and repeated queries cost nothing.
  • Accessibility is a requirement, not a polish item: follow the WAI-ARIA combobox pattern (role="combobox", aria-expanded, aria-activedescendant, role="listbox"/option) with full keyboard support.
  • Make it reusable with a headless API: the consumer passes a fetchSuggestions(query, signal) function and a renderItem function, and the component owns state, keyboard handling and ARIA.

1. Requirements

Clarify the scope before designing anything. Good questions to ask:

  • Where do suggestions come from: a server API, a local list, or both (recent searches)?
  • How many results do we show? Do we group them (products, categories, recent)?
  • Is this one search box, or a reusable component for many teams?
  • Which devices? Mobile matters for the keyboard and the popup size.

Functional

  • Show suggestions as the user types, highlighting the matched part.
  • Select with mouse, touch, or keyboard (↑/↓, Enter, Escape).
  • Show loading, empty and error states.
  • Optionally: recent searches when the input is focused and empty.

Non-functional

  • Perceived latency: suggestions should appear within ~100-300 ms of the user pausing.
  • Network efficiency: a fast typist shouldn't trigger 10 requests a second.
  • Accessibility: works with a screen reader and keyboard only.
  • Robustness: slow or failing APIs never show wrong or stale results.

2. Architecture

Loading diagram...
  • Input: a controlled <input>. It reports text changes and key presses to the controller.
  • Controller (a hook, e.g. useAutocomplete): holds the state, debounces, checks the cache, calls the fetcher, ignores stale responses, and handles keyboard navigation.
  • Cache: an in-memory map from normalized query to results, with a size limit.
  • Suggestion list: a popup positioned under the input. It renders items and reports hover and click.

Keeping the controller headless (no markup) is the key to reusability: one team can render product cards, another plain text, and both get the same correct behavior.

3. Data model

ts
type Suggestion = {
  id: string
  label: string
  /** What goes into the input or the URL when picked. */
  value: string
  type?: 'product' | 'category' | 'recent'
}

type AutocompleteState = {
  query: string
  status: 'idle' | 'loading' | 'success' | 'error'
  results: Suggestion[]
  /** Index of the keyboard-highlighted option, or -1. */
  activeIndex: number
  isOpen: boolean
}

// Cache: normalized query ("iphone 15") -> results, least recently used evicted first.
type SuggestionCache = Map<string, { results: Suggestion[]; fetchedAt: number }>

Normalize cache keys (trim, lowercase, collapse spaces) so "iPhone " and "iphone" share an entry. Give entries a TTL if results change often.

4. Interface (API)

Server

http
GET /api/suggestions?q=iph&limit=8
json
{
  "query": "iph",
  "results": [{ "id": "p_1", "label": "iPhone 15", "value": "iphone-15", "type": "product" }]
}

Echoing the query back lets the client double-check which request a response belongs to. The server should be fast (prefix index, cached hot queries) and return few results: the UI shows 5-10.

Component

tsx
<Autocomplete<Suggestion>
  fetchSuggestions={(query, signal) => api.suggest(query, { signal })}
  renderItem={(item, { active }) => <ProductRow item={item} active={active} />}
  onSelect={(item) => navigate(`/search?q=${item.value}`)}
  minQueryLength={2}
  debounceMs={250}
  placeholder="Search products"
/>

5. Optimizations and deep dives

Debounce and minimum length

Debouncing waits until the user pauses typing. 200-300 ms is a common choice: short enough to feel live, long enough to skip most intermediate keystrokes. Throttling is the alternative when you want results while typing continuously, at most once per interval. Skip queries shorter than 2 characters, which match too much to be useful.

Race conditions

Without protection, this happens: the user types ip, then iph. The ip request is slow and its response arrives after iph, overwriting the correct results.

ts
useEffect(() => {
  if (query.length < minQueryLength) return
  const controller = new AbortController()
  const timer = setTimeout(async () => {
    const cached = cache.get(key(query))
    if (cached) return setResults(cached.results)
    try {
      const results = await fetchSuggestions(query, controller.signal)
      cache.set(key(query), { results, fetchedAt: Date.now() })
      setResults(results)
    } catch (error) {
      if (!controller.signal.aborted) setError(error)
    }
  }, debounceMs)
  // A newer query cancels both the pending timer and the in-flight request.
  return () => {
    clearTimeout(timer)
    controller.abort()
  }
}, [query])

Aborting saves bandwidth and guarantees a stale response can't call setResults. A request-id counter ("only apply the response if id === latestId") is an equivalent alternative when the transport can't be aborted.

Caching

  • In-memory LRU per session (50-100 entries) makes backspacing instant.
  • Prefix reuse: with plain prefix matching, if iph returned fewer results than the limit, the results for ipho are a subset you can filter locally, with no request.
  • HTTP caching (Cache-Control: max-age=60) and a CDN help for popular queries shared by all users.
  • Prefetch the top suggestions or recent searches on focus.

Accessibility (the combobox pattern)

html
<input
  role="combobox"
  aria-expanded="true"
  aria-controls="search-listbox"
  aria-autocomplete="list"
  aria-activedescendant="option-2"
/>
<ul id="search-listbox" role="listbox">
  <li id="option-1" role="option" aria-selected="false">iPhone 15</li>
  <li id="option-2" role="option" aria-selected="true">iPhone 15 Pro</li>
</ul>
  • Focus stays in the input while ↑/↓ move the highlight. aria-activedescendant tells screen readers which option is active.
  • Enter selects, Escape closes (and clears on a second press), Tab moves on.
  • Announce the result count with a polite live region ("8 suggestions available").
  • Don't rely on hover alone, and keep hit targets large on touch.

Rendering and UX

  • Highlight the matched substring, but escape the text: never inject raw HTML from the API (XSS).
  • Keep the list short. If it can be long, virtualize it.
  • Show a subtle spinner only if loading takes more than ~150 ms, to avoid flicker.
  • On mobile, consider a full-screen search view so the list isn't hidden by the keyboard.
  • In RTL languages, align the popup to the input's start edge, and make sure mixed Hebrew and English text renders in the right direction.

Errors and offline

Show a small inline error and keep the last good results. Retry on the next keystroke rather than with an aggressive loop. Never block the user from submitting the full search.

Common follow-ups

  • "How would you support 1 million items with no server?" Load a compact index once (or a trie) into a Web Worker and search there, so the main thread stays free.
  • "How do you rank results?" That's mostly a server concern: popularity, personalization, typo tolerance (fuzzy matching). The client can boost recent searches.
  • "How do you measure success?" Click-through rate on suggestions, time to first result, zero-result rate, and the share of searches that used a suggestion.

What interviewers look for

  • Clarifying questions first, and a clear split between functional and non-functional requirements.
  • Naming the race condition and solving it, not only "add a debounce".
  • Caching with a sensible key and eviction strategy.
  • Accessibility treated as a core requirement, with the combobox pattern and keyboard support.
  • A reusable API that separates behavior (the hook) from presentation (render props).

Was this helpful?