Searchable Dropdown Input with Live Async Suggestions in React
Data Structure DesignModel answerLast updated
Implement a React search box whose dropdown fills with suggestions from an abortable async source and works fully by keyboard and mouse, without ever showing outdated results.
Task
Implement a reusable search-as-you-type component in React. As the user enters text, a dropdown below the input lists matching suggestions retrieved from an asynchronous source. The list must be fully operable with the keyboard as well as the mouse.
The data source is supplied as a function. It resolves to the suggestions for a given query and should cancel its work when the abort signal fires:
type FetchSuggestions = (query: string, signal: AbortSignal) => Promise<string[]>;
Required behavior
- While the user types, show the suggestions that correspond to the current text in a dropdown under the input.
- Arrow Up / Arrow Down move a highlight through the listed suggestions.
- Enter chooses the highlighted suggestion.
- Escape closes the dropdown.
- Clicking a suggestion chooses it.
- Choosing a suggestion must: write its text into the input, close the dropdown, and notify the parent component (for example through an
onSelectcallback).
Constraints
- Use React function components and hooks only.
- Do not use a third-party autocomplete or combobox library. The behavior itself is what is being evaluated.
Decisions to state out loud
Because the spec leaves several things open, explain which choice you make and why:
- Is the request debounced, and is there a minimum query length?
- Are results cached per query?
- What does Enter do when nothing is highlighted?
- Does arrow navigation wrap around at either end?
- What does the dropdown display while loading, when nothing matches, and when the request fails?
- Is screen-reader support included?
Provide the component code and walk through your design, including how you would test it.
Hints
Hint 1
Keep a small state model: the input text, the suggestion list, a status (idle, loading, error), an open flag and a highlighted index. Reset the highlight whenever the list changes.
Hint 2
Fetch inside an effect keyed on the (debounced) query. Create an AbortController in the effect and abort it in the cleanup, and also ignore any result that arrives after cleanup has run. That guarantees an old response can never overwrite a newer one.
Hint 3
Clicking an option blurs the input before the click fires, which can close the list too early. Handle onMouseDown on options (with preventDefault), or delay closing on blur.
Hint 4
For accessibility, use role=combobox on the input with aria-expanded, aria-controls and aria-activedescendant, a role=listbox container, and role=option with aria-selected on each item.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Treat the component as a small state machine fed by an async effect, plus a keyboard handler. The two things that most often go wrong are stale responses and blur-versus-click conflicts, so design around those first.
State model
text: the controlled input value.items: the latest suggestions.status:idle | loading | error.open: whether the dropdown is visible.active: index of the highlighted option,-1for none.
Derived: show "No matches" when status === "idle", the query is long enough, and items.length === 0.
Fetching without stale results
Debounce the text (about 200-300 ms) into a query value, and require a minimum length (1-2 characters) to avoid noisy requests. Then:
useEffect(() => {
if (query.length < MIN_LEN) { setItems([]); setStatus("idle"); return; }
const ctrl = new AbortController();
let cancelled = false;
setStatus("loading");
fetchSuggestions(query, ctrl.signal)
.then(res => { if (cancelled) return; setItems(res); setActive(-1); setStatus("idle"); })
.catch(err => { if (cancelled || err?.name === "AbortError") return; setStatus("error"); });
return () => { cancelled = true; ctrl.abort(); };
}, [query, fetchSuggestions]);
Cleanup runs when the query changes and when the component unmounts. Aborting frees the network work, and the cancelled flag protects against sources that ignore the signal. Together they make out-of-order responses harmless: only the effect belonging to the latest query can write state. Never rely on abort alone.
Optional cache: a useRef(new Map<string, string[]>()). Check it before fetching and fill it on success. Trade-off: fewer requests and instant repeats, but possibly stale data and unbounded memory, so cap the size (simple LRU) or add a TTL.
Keyboard behavior
function onKeyDown(e: React.KeyboardEvent) {
switch (e.key) {
case "ArrowDown":
e.preventDefault();
if (!open) { setOpen(true); break; }
setActive(i => (items.length ? (i + 1) % items.length : -1));
break;
case "ArrowUp":
e.preventDefault();
setActive(i => (items.length ? (i <= 0 ? items.length - 1 : i - 1) : -1));
break;
case "Enter":
if (open && active >= 0) { e.preventDefault(); choose(items[active]); }
break;
case "Escape":
setOpen(false); setActive(-1);
break;
}
}
function choose(value: string) {
setText(value); setOpen(false); setActive(-1); onSelect(value);
}
Decisions: wrapping is enabled because it is the common expectation for short lists; Enter with no highlight does nothing special inside the component, so a surrounding form can still handle it. Calling preventDefault on arrows stops the caret jumping to the start or end of the text.
One subtlety: after choose, setting text would normally trigger a new fetch for the chosen value and reopen the list. Guard this with a ref (justChose) that suppresses the next fetch/open, or only open the list on user-initiated onChange.
Mouse and focus
When the user presses an option, the input blurs before click fires. If blur closes the list, the option unmounts and the click is lost. Fix by using onMouseDown={e => e.preventDefault()} on the list so focus stays in the input, and onClick on each option to call choose. Close on blur otherwise. Also update active on onMouseEnter so mouse and keyboard highlights stay in sync.
UI states
- Loading: a "Loading..." row, or keep the previous items dimmed to avoid flicker.
- Empty: "No matches" row, announced via a polite live region.
- Error: a message with a retry action; do not clear what the user typed.
Accessibility
Follow the ARIA combobox pattern:
- Input:
role="combobox",aria-expanded={open},aria-controls={listId},aria-autocomplete="list",aria-activedescendant={active >= 0 ? optionId(active) : undefined}. - List:
role="listbox"withid={listId}. - Options:
role="option", uniqueid,aria-selected={i === active}. - DOM focus never leaves the input; the highlight is exposed through
aria-activedescendant. Scroll the active option into view withscrollIntoView({ block: "nearest" }).
Complexity
Rendering is O(n) in the number of suggestions. Debouncing bounds requests to roughly one per pause in typing instead of one per keystroke.
Testing plan
- Use fake timers to verify debounce and the minimum length.
- Mock
fetchSuggestionswith controllable promises: resolve the second request before the first and assert the UI shows the second's results (the stale-response test). - Assert abort is called on query change and on unmount, and that no state update occurs after unmount.
- Simulate ArrowDown/ArrowUp including wrap, Enter, Escape, and a click; assert
onSelectis called once with the right value and the list closes. - Check loading, empty and error rendering, and ARIA attributes (
aria-activedescendantfollows the highlight).
Common mistakes
- Only checking
textafter the response, or forgetting cleanup, so late responses overwrite newer ones. - Closing on blur and losing mouse clicks.
- Not resetting
activewhen the list changes, leaving an out-of-range index. - Re-fetching and reopening after a selection.
- Fetching on every keystroke with no debounce or minimum length.
- Missing
preventDefaulton arrow keys or Enter inside a form.