Live coding ยท 45 minutes
Autocomplete with debounce
Build a search box with suggestions in React in 45 minutes, with no autocomplete library. As the user types, request suggestions from an API: a public test API, or a fake function that returns a promise after a random delay. Requests are debounced, and a late response must never replace a newer one. The user moves through the suggestions with the arrow keys and chooses one with Enter. Explain your decisions while you code, as in a live round.
Requirements
- Typing sends a request only after a pause of about 300 ms, not on every key
- A new request aborts the one before it with AbortController, or the late response is ignored
- Up and Down arrows move the highlight, Enter chooses the item, Escape closes the list
- A click on a suggestion chooses it
- Loading, no results and error states are shown
- An empty input sends no request and closes the list
- The timer and the request are cleaned up when the query changes and when the component unmounts
What reviewers look for
- A correct debounce in React: the timer is cleared in the effect cleanup
- The race condition is named and handled, not left to chance
- Small state: query, items, status and active index
- Keyboard handling that keeps focus in the input
- Basic ARIA: combobox on the input, listbox and option in the list, aria-activedescendant for the highlighted item
- You test the slow network case yourself and say what you see
Check before you hand it in
- In the network panel, typing a word fast sends one request, not one for each letter
- With random delays, the list always matches the text that is in the input now
- Arrow keys move the highlight, Enter chooses the item and Escape closes the list, and focus stays in the input
- Loading, no results and a failed request each show a clear message
- The effect cleanup clears the timer and aborts the request, and an aborted request is not shown as an error
- I explained each decision aloud, including why the race condition happens
- Debounced requests, stale responses handled and a list I can choose from all worked within 45 minutes
If there is time
- Cache results by query, so Backspace shows the earlier list at once
- Highlight the part of each suggestion that matches the query
- Move the logic into a reusable hook, for example useAutocomplete
- Announce the number of results to screen readers with a live region