
Autocomplete is one of the most common frontend interview questions out there. I’ve been asked some version of it more than once, and it’s on almost every list of app-design questions.
It’s a great question because it looks easy. An input, a fetch, a dropdown. But it quietly tests debouncing, race conditions, caching, keyboard handling, and accessibility.
Now swap the backend for an AI model that suggests completions. Every weakness gets amplified. Requests are slower, more expensive, and less predictable. Here’s how I’d build it, step by step, the way I’d walk through it in an interview.
Requirements I’d clarify first
- Do suggestions come from a search index, an AI model, or both? (I’ll assume both: fast search results plus AI suggestions.)
- Minimum characters before we fetch? (I’ll say 2.)
- Show suggestions in a dropdown, inline “ghost text”, or both?
- Keyboard support: arrow keys, Enter to select, Escape to close, Tab to accept ghost text.
- Any limits on cost? AI suggestions on every keystroke can get expensive fast.
Bug #1: Too many requests
A naive implementation fetches on every keystroke. Typing “react hooks” fires 11 requests. With an AI backend, that’s 11 model calls for one query.
The fix is debouncing: wait until the user pauses typing (usually 200-300ms) before fetching. If you need a refresher, see debounce vs throttle and practice it with Debounce I.
Bug #2: The race condition
This is the one interviewers are really looking for. Even with debouncing, requests can overlap, and responses don’t come back in the order you sent them.

The user types “rea”, pauses, then types “react”. The “rea” request is slow. The “react” request is fast. “react” results show up first, and then the stale “rea” results arrive and overwrite them. The user sees suggestions for something they’re no longer typing.
There are two common fixes, and you should know both:
- Abort the previous request with an
AbortControllerwhen a new one starts. This also saves bandwidth and, with a server that propagates the abort, model cost. - Ignore stale responses by checking that the response matches the latest query before updating state. Useful when the API can’t be cancelled.
I like doing both. Abort for efficiency, and a staleness check as a safety net.
The core logic
I’d keep the fetching logic separate from the UI. It’s easier to test, and in an interview it shows you think about separation of concerns.
export function createSuggester({ fetchSuggestions, delay = 250, minChars = 2, cacheSize = 50 }) {
const cache = new Map(); // Map keeps insertion order, so it works as a tiny LRU
let timer = null;
let controller = null;
function remember(query, results) {
cache.delete(query);
cache.set(query, results);
if (cache.size > cacheSize) cache.delete(cache.keys().next().value);
}
function cancel() {
clearTimeout(timer);
controller?.abort();
controller = null;
}
function suggest(rawQuery, { onResults, onError, onLoading }) {
cancel();
const query = rawQuery.trim().toLowerCase();
if (query.length < minChars) {
onLoading?.(false);
return onResults([]);
}
if (cache.has(query)) {
const results = cache.get(query);
remember(query, results); // refresh its LRU position
onLoading?.(false);
return onResults(results);
}
timer = setTimeout(async () => {
controller = new AbortController();
const { signal } = controller;
onLoading?.(true);
try {
const results = await fetchSuggestions(query, { signal });
if (signal.aborted) return; // a newer query started while we awaited
remember(query, results);
onResults(results);
} catch (err) {
if (err.name !== 'AbortError') onError?.(err);
} finally {
if (!signal.aborted) onLoading?.(false);
}
}, delay);
}
return { suggest, cancel };
}
A few details worth calling out in the interview:
- Normalizing the query (trim, lowercase) makes the cache much more effective.
- Cached results skip the debounce. If we already have the answer, there’s no reason to wait.
- The
signal.abortedcheck afterawaithandles the tiny window where the response resolved but a new query started before our code continued. - Bounded cache. An unbounded Map is a memory leak in a long-lived page.
The UI: accessibility matters here
This is where a lot of candidates lose points. An autocomplete is a combobox, and screen reader users rely on the right ARIA attributes to know suggestions exist and which one is active.
function Autocomplete({ suggester, onSelect }) {
const [query, setQuery] = useState('');
const [results, setResults] = useState([]);
const [activeIndex, setActiveIndex] = useState(-1);
const [open, setOpen] = useState(false);
const listId = useId();
useEffect(() => () => suggester.cancel(), [suggester]);
function handleChange(e) {
const value = e.target.value;
setQuery(value);
setActiveIndex(-1);
suggester.suggest(value, {
onResults: (r) => { setResults(r); setOpen(r.length > 0); },
onError: () => setOpen(false),
});
}
function select(item) {
setQuery(item.label);
setOpen(false);
onSelect(item);
}
function handleKeyDown(e) {
if (!open) return;
if (e.key === 'ArrowDown') {
e.preventDefault();
setActiveIndex((i) => (i + 1) % results.length);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
setActiveIndex((i) => (i <= 0 ? results.length - 1 : i - 1));
} else if (e.key === 'Enter' && activeIndex >= 0) {
e.preventDefault();
select(results[activeIndex]);
} else if (e.key === 'Escape') {
setOpen(false);
}
}
return (
<div className="autocomplete">
<input
role="combobox"
aria-expanded={open}
aria-controls={listId}
aria-autocomplete="list"
aria-activedescendant={activeIndex >= 0 ? `${listId}-${activeIndex}` : undefined}
value={query}
onChange={handleChange}
onKeyDown={handleKeyDown}
/>
{open && (
<ul id={listId} role="listbox">
{results.map((item, i) => (
<li
key={item.id}
id={`${listId}-${i}`}
role="option"
aria-selected={i === activeIndex}
onMouseDown={(e) => e.preventDefault()} // keep focus in the input
onClick={() => select(item)}
>
{item.label}
</li>
))}
</ul>
)}
</div>
);
}
The onMouseDown with preventDefault is a small detail I love seeing. Without it, clicking an option blurs the input first, and if you close the list on blur, the click never lands.
Also note that focus stays in the input the whole time. Arrow keys move a virtual highlight using aria-activedescendant, so the user can keep typing.
Adding the AI part: ghost text
Search results come from an index and are fast. AI suggestions are slower but can complete the user’s intent (“how to cancel a fetch req” → “uest with AbortController”). A nice pattern is to show the AI completion as faded inline text that the user accepts with Tab.
Rules I’d follow:
- Longer debounce for AI. Search can fire at 200ms. AI completion should wait for a clearer pause (around 500ms) because it’s slower and costs money.
- Any keystroke invalidates the ghost text, unless the user typed exactly the next characters of the suggestion, in which case you just trim it.
- Tab accepts, Escape dismisses. Don’t hijack Tab when there’s no suggestion, or keyboard users can’t leave the field.
- Stream it if it’s long, but for short completions, a single response is simpler and fine.
- Cap cost. Minimum characters, a per-session request budget, and a cache keyed on the prefix.
The nice thing is that createSuggester works unchanged for this. You create a second instance with a longer delay and an AI-backed fetchSuggestions.
const searchSuggester = createSuggester({ fetchSuggestions: searchIndex, delay: 200 });
const aiSuggester = createSuggester({ fetchSuggestions: aiComplete, delay: 500, minChars: 4 });
Edge cases interviewers ask about
| Edge case | What I’d do |
|---|---|
| User types fast, then deletes everything | Cancel pending requests, clear and close the list |
| Network error | Close the list quietly; don’t show an error for every keystroke |
| Same query typed again | Serve from cache, no debounce |
| Component unmounts mid-request | Cancel in the cleanup effect |
| Highlighting the match | Split the label safely into text nodes; never build HTML strings from user input |
| Very long result lists | Limit to ~10 results, or virtualize |
| Mobile | Bigger tap targets, and make sure the list isn’t covered by the keyboard |
That highlighting row is its own common interview question. You can practice it with Highlight Matches.
How I’d present this in the interview
“I’ll debounce input so we don’t fire on every keystroke, abort the previous request when a new one starts so stale results can’t overwrite newer ones, and cache by normalized query. The input is a combobox with aria-activedescendant, so focus stays in the input while arrow keys move the highlight. For AI suggestions I’d use a longer debounce, a minimum length, and a request budget to control cost.”
Then build it in that order: get the input and dropdown working, add debouncing, add cancellation, add keyboard support, add caching. Talk through each step as you go. If you run out of time, you’ve still covered the most important parts.
You can practice the base version with the Autocomplete Search List question on FrontendLead, which comes with tests that check exactly these behaviors. For the design version, the app design questions guide is a good next read.
And that’s it, folks. Autocomplete is a small component with a lot of depth, which is exactly why interviewers keep asking it. Adding AI doesn’t change the fundamentals. It just makes getting them wrong more expensive.
