Build a Race-Safe, Screen-Reader-Friendly Typeahead Combobox
System DesignModel answerLast updated
Build a generic React typeahead that debounces input, discards out-of-order responses, follows the ARIA combobox pattern, and supports full keyboard control.
Task
Build a reusable typeahead (combobox) component in React and TypeScript. As the user types, the component waits for a short pause, requests matching suggestions from an async function, and shows them in a dropdown. The user can pick a suggestion with the mouse or the keyboard.
Network latency is unpredictable, so replies can arrive out of order. For example, the reply for "ap" may land after the reply for "appl". The dropdown must never show results that belong to an older query than the one currently in the input.
Required behavior
- Out-of-order protection. A late reply for an outdated query must never overwrite newer state. Use
AbortController, a monotonically increasing request counter, or an equivalent technique. - Debounce. Wait
debounceMs(default300) after the last keystroke before fetching. - ARIA combobox pattern.
- The input has
role="combobox",aria-autocomplete="list",aria-expanded, andaria-controlspointing at the listbox id. - The popup has
role="listbox"and every suggestion hasrole="option". - The highlighted option is exposed through
aria-activedescendant. Real DOM focus stays in the input.
- The input has
- Keyboard.
ArrowDown/ArrowUpmove the highlight (wrapping or clamping is acceptable, but state which you chose).Enterselects the highlighted item and closes the popup.Escapecloses the popup and leaves the typed text alone.
- States. Show loading, empty ("No results found"), and error states. Close the popup on outside click or when focus leaves the component.
Signature
interface AutocompleteProps<T> {
fetchSuggestions: (query: string, signal?: AbortSignal) => Promise<T[]>;
renderOption: (item: T) => React.ReactNode;
getOptionKey: (item: T) => string;
onSelect: (item: T) => void;
debounceMs?: number;
placeholder?: string;
}
function Autocomplete<T>(props: AutocompleteProps<T>): JSX.Element;
Example
t = 0ms: user types"b".t = 100ms: user types"ba".t = 400ms: the debounce fires and exactly one request, for"ba", is sent.- The user presses
ArrowDown: the first suggestion is highlighted andaria-activedescendantpoints to its id. - The user presses
Enter:onSelectreceives that item and the popup closes.
Edge cases to handle
- Empty input: do not fetch, and close the popup right away.
- Failed request: catch the rejection and show an accessible error message.
- Unmount: clear pending timers and abort in-flight requests.
Explain your design, then give the implementation, its complexity, and the pitfalls you guarded against.
Hints
Hint 1
Tie the timer and the AbortController to a single useEffect keyed on the query. The effect's cleanup then both clears the timer and aborts the request, which covers new keystrokes and unmount with the same code.
Hint 2
Check controller.signal.aborted after the await, before calling any setState. That way a stale reply is dropped even if the supplied fetchSuggestions ignores the signal.
Hint 3
For accessibility, keep DOM focus on the input and move only aria-activedescendant. Prevent the default on option mousedown so clicking an option does not blur the input before the click registers, and put loading/empty/error text in a role="status" live region.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Split the component into three independent concerns.
- Query pipeline. One effect depends on the query. It starts a timer, and when the timer fires it issues a request tied to an
AbortController. The effect's cleanup clears the timer and aborts the controller. React always runs the previous cleanup before the next effect body, so by the time the request for"appl"exists, the one for"ap"is already marked aborted. The commit rule is simple: after theawait, ifsignal.abortedthen return without touching state. - Interaction state.
isOpen,activeIndex,items, andstatus(idle | loading | success | error). Keyboard and mouse handlers only update these. - ARIA wiring. DOM focus never leaves the input. The highlighted option is communicated with
aria-activedescendant. Arole="status"region announces loading, empty, and error text so screen-reader users get the same feedback as sighted users.
Why it is correct
- No stale data. The abort check after the
awaitmeans ordering of replies is irrelevant. Only the request belonging to the latest effect run can ever commit. This still works iffetchSuggestionsignores the signal, because the guard is in our code, not the fetcher's. - No flash of old results.
onChangesynchronously clearsitemsand setsstatustoloading, so the previous query's list is never shown beside new text. - Debounce. Every keystroke re-runs the effect, which clears the previous timer. In the example,
"b"then"ba"yields a single request for"ba"at about 400ms. - Stable effect. The latest
fetchSuggestionsis stored in a ref. A parent that passes an inline arrow function will not retrigger the fetch on every render. - Lifecycle. Unmount runs the same cleanup, so there are no leaked timers or requests. The outside-click listener exists only while the popup is open.
Implementation
import React, { useEffect, useId, useRef, useState } from "react";
type Status = "idle" | "loading" | "success" | "error";
export interface AutocompleteProps<T> {
fetchSuggestions: (query: string, signal?: AbortSignal) => Promise<T[]>;
renderOption: (item: T) => React.ReactNode;
getOptionKey: (item: T) => string;
onSelect: (item: T) => void;
debounceMs?: number;
placeholder?: string;
}
export function Autocomplete<T>({
fetchSuggestions,
renderOption,
getOptionKey,
onSelect,
debounceMs = 300,
placeholder,
}: AutocompleteProps<T>): JSX.Element {
const [query, setQuery] = useState("");
const [items, setItems] = useState<T[]>([]);
const [status, setStatus] = useState<Status>("idle");
const [isOpen, setIsOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(-1);
const baseId = useId();
const listboxId = `${baseId}-listbox`;
const optionId = (i: number) => `${baseId}-opt-${i}`;
const rootRef = useRef<HTMLDivElement>(null);
// Always call the latest fetcher without re-running the effect.
const fetchRef = useRef(fetchSuggestions);
useEffect(() => {
fetchRef.current = fetchSuggestions;
});
// Debounced, cancellable request. Cleanup handles new input and unmount.
useEffect(() => {
const q = query.trim();
if (!q) return;
const controller = new AbortController();
const timer = window.setTimeout(async () => {
try {
const result = await fetchRef.current(q, controller.signal);
if (controller.signal.aborted) return; // stale reply
setItems(result);
setStatus("success");
setActiveIndex(-1);
} catch {
if (controller.signal.aborted) return; // cancelled, not a failure
setItems([]);
setStatus("error");
}
}, debounceMs);
return () => {
window.clearTimeout(timer);
controller.abort();
};
}, [query, debounceMs]);
// Outside click closes the popup; listener lives only while open.
useEffect(() => {
if (!isOpen) return;
const onDown = (e: MouseEvent) => {
if (!rootRef.current?.contains(e.target as Node)) {
setIsOpen(false);
setActiveIndex(-1);
}
};
document.addEventListener("mousedown", onDown);
return () => document.removeEventListener("mousedown", onDown);
}, [isOpen]);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const value = e.target.value;
const hasText = value.trim() !== "";
setQuery(value);
setItems([]); // never show the previous query's results
setActiveIndex(-1);
setStatus(hasText ? "loading" : "idle");
setIsOpen(hasText);
};
const choose = (index: number) => {
if (index < 0 || index >= items.length) return;
onSelect(items[index]);
setIsOpen(false);
setActiveIndex(-1);
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
const n = items.length;
switch (e.key) {
case "ArrowDown":
if (!n) return;
e.preventDefault();
setIsOpen(true);
setActiveIndex((i) => (i + 1) % n);
break;
case "ArrowUp":
if (!n) return;
e.preventDefault();
setIsOpen(true);
setActiveIndex((i) => (i <= 0 ? n - 1 : i - 1));
break;
case "Enter":
if (isOpen && activeIndex >= 0) {
e.preventDefault();
choose(activeIndex);
}
break;
case "Escape":
setIsOpen(false);
setActiveIndex(-1);
break;
}
};
const message =
status === "loading" ? "Loading suggestions..."
: status === "error" ? "Something went wrong. Please try again."
: status === "success" && items.length === 0 ? "No results found"
: status === "success" ? `${items.length} suggestions available`
: "";
return (
<div ref={rootRef}>
<input
type="text"
value={query}
placeholder={placeholder}
aria-label={placeholder ?? "Search"}
role="combobox"
aria-autocomplete="list"
aria-expanded={isOpen}
aria-controls={listboxId}
aria-activedescendant={activeIndex >= 0 ? optionId(activeIndex) : undefined}
onChange={handleChange}
onKeyDown={handleKeyDown}
/>
<ul id={listboxId} role="listbox" hidden={!isOpen || items.length === 0}>
{items.map((item, i) => (
<li
key={getOptionKey(item)}
id={optionId(i)}
role="option"
aria-selected={i === activeIndex}
onMouseDown={(e) => e.preventDefault()} // keep focus in input
onClick={() => choose(i)}
>
{renderOption(item)}
</li>
))}
</ul>
<div role="status" aria-live="polite">
{isOpen || status === "error" ? message : ""}
</div>
</div>
);
}
Complexity
- Per keystroke: O(1) work, and at most one request per pause of
debounceMs. - Rendering is O(n) in the number of suggestions. Arrow navigation is O(1) state work.
- Memory is O(n) for the current suggestions only. Nothing accumulates across queries.
Trade-offs
- AbortController vs. sequence counter. Aborting also frees the network connection and server work, but it depends on the fetcher honoring the signal. The post-
awaitabortedcheck gives counter-like safety either way. A counter alone is simpler but leaves wasted requests running. - Wrap vs. clamp. Wrapping is quicker for long lists. Clamping is more predictable for some screen-reader users. Either is acceptable if documented.
- Caching. An LRU map keyed by query would make backspacing instant. It adds invalidation concerns, so treat it as an optional extension.
- Large lists. Cap results (for example 10 to 20) or virtualize, and keep
aria-activedescendantpointing at a mounted node.
Common mistakes
- Setting state from a stale response because only the timer was cleared, not the in-flight request.
- Showing old suggestions next to new text while loading.
- Putting the fetcher in the effect's dependency array, which refetches on every parent render.
- Letting the option's
mousedownblur the input, so the popup closes beforeclickfires. - Moving real DOM focus into options instead of using
aria-activedescendant. - Treating an aborted request as an error and flashing an error message.
- Rendering
aria-controlsthat points to a listbox element that does not exist. Keep the listbox in the DOM and usehidden. - Relying on the placeholder as the accessible name instead of providing an
aria-labelor a real label. - Not calling
preventDefaulton arrow keys, so the caret jumps to the start or end of the text.