All questions

Autocomplete III

Premium

Autocomplete III

Build a production-grade autocomplete as a single React component. This is the interview boss level: the input fires a network request as you type, but you must not hammer the server on every keystroke, must not pay for the same query twice, must be fully keyboard-drivable, and must highlight the part of each result that matched. Four concerns — debounce, cache, keyboard, highlight — layered onto one text field.

Task

The starter App.tsx renders an inert input over a simulated searchAPI (≈350ms, case-insensitive substring match). Make it a real autocomplete:

  1. Debounce the fetch. On every change, store the query, then wait 300ms of quiet before searching. A new keystroke cancels the pending search.
  2. Cache per query. Keep a Map<string, string[]> in a useRef. Before fetching, check the cache; a repeat query returns instantly with a cached status instead of paying the 350ms again.
  3. Keyboard navigation. ArrowDown / ArrowUp move an active index through the list with wraparound, Enter commits the active option, Escape closes the list.
  4. Highlight the match. In each option, wrap the substring that matched the query in a `<span className="hl">` so it stands out.

Examples

  • Type scr slowly: after you stop, a Searching… line appears, then JavaScript and TypeScript show with Scr highlighted in green.
  • Clear the box and type scr again: results appear instantly and the status reads cached — no second network wait.
  • Press ArrowDown twice, ArrowUp once, then Enter: the highlighted row fills the input and the list closes.

Notes

  • The cache is not state. It lives in a useRef so writing to it never triggers a re-render; only setResults should repaint the list.
  • One debounce timer at a time. The useEffect cleanup must clear the previous timeout, or stale searches will land out of order.
  • The dataset is fixed and small. searchAPI and the LANGUAGES list are provided — don't fetch anything real; focus on the four behaviours above.

Unlock the solution & editor

  • Runnable editor + tests

    Solve in the browser with instant Jest feedback.

  • Detailed solutions

    Walkthroughs, edge cases, and complexity notes.

  • Multi-framework variants

    React, Vue, Vanilla, Angular — same question, different stacks.

Upgrade to Premium