A text input that suggests completions as the user types. Every search bar, tag picker, and command palette on the web uses this pattern. The challenge is not the suggestions — it's orchestrating debounce, race conditions, keyboard cycling, accessibility, and cache with only a handful of state variables.
An autocomplete — also called typeahead or search-as-you-type — is a text input that displays a filtered list of suggestions below the input while the user is typing. Google's search bar is the canonical example. GitHub's user/ repo picker is another. Every design system ships one: MUI calls it Autocomplete, Ant Design has AutoComplete, and Radix UI provides a Combobox primitive.
What looks like a simple text box hides a surprising amount of complexity. The component must debounce user input, fetch suggestions from a server without racing responses, cache previous queries, support full keyboard navigation, expose a customizable rendering API, and comply with the WAI-ARIA Combobox pattern. One missed edge case — a slow network response overwriting a newer query — and the user sees stale results.
Here is the API shape I settled on — a compound component where the root manages state and children define the visual layers:
The consumer provides a fetchSuggestions function and renders sub-components. The hard work — debounce, cache, race-condition handling — happens inside the root. Let's walk through how I arrived at this design.
1 · Requirements & Scoping
The first thing an interviewer will ask: "What are we building?" Here are the clarifying questions I would ask in return, and the answers that shaped the component.
Functional requirements
Suggest as you type: As the user types, a list of suggestions appears below the input. Suggestions are fetched from a server with debounce.
Keyboard navigation: Arrow keys cycle through suggestions. Enter selects the highlighted item. Escape closes the list. Tab moves to the next field.
Mouse interaction: Clicking a suggestion selects it. Clicking outside closes the list.
Custom rendering: Consumers supply their own suggestion UI. Some need text-only results; others need icons, avatars, or rich media.
Minimum query length: Only fetch suggestions after the user has typed at least N characters (default 2).
Server-driven suggestions: The component calls an HTTP API that returns suggestions for a query. No client-side filtering of a static list.
Non-functional requirements
Performance: No layout thrashing on typing. Debounced API calls. No unnecessary re-renders. Cached responses for previously-searched queries.
Accessibility: Full compliance with WAI-ARIA 1.2 Combobox pattern. Screen readers must announce the number of suggestions and which one is highlighted.
Race-condition safety: A slow response for "fo" must not overwrite the results for "foo" when the user has already typed further.
Bundle size: No external dependencies for core logic. Debounce, cache, and key handlers must be implemented in-house to keep the component tree-shakable.
Tip
I deliberately scoped out client-side fuzzy filtering. The GFE source notes that "fuzzy search is not needed for the initial version." If the consumer wants to filter a local dataset, they can preload results and implement filtering inside fetchSuggestions. The component should not assume where data comes from.
2 · Architecture & High-Level Design
The central architectural decision is: who owns the fetching logic? The simplest approach is to put everything inside the input component — keystroke handler, debounce, API call, cache read. But that violates single responsibility and makes it impossible to test the fetching layer independently.
I settled on a layered architecture with three tiers. At the top is the compound component root, which holds state and coordinates children. Below it sits the controller layer — a plain TypeScript class that handles debounce, cache reads, and API dispatch. At the bottom is the network layer, which is just the consumer-provided fetchSuggestions function.
Figure 1 — The compound component API for Autocomplete. The root owns state and delegates rendering to sub-components. A central controller handles debounce, API calls, and cache reads.
I considered three patterns for the API shape:
Option A: All-in-one (rejected)
A single <Autocomplete items={[...]} /> prop that accepts data directly. Simple for static datasets, but falls apart when data comes from an API. The consumer has no control over loading or error states, and custom rendering requires escape hatches that bloat the API surface.
Option B: Controlled input (rejected)
Expose value, onChange, and suggestions — the consumer manages everything. This is the most flexible but also the most tedious. Every autocomplete consumer must implement debounce, cache, and keyboard handling from scratch. The GFE source notes: "a component that requires too much boilerplate will be rejected by developers."
Option C: Compound + fetchSuggestions (chosen)
The consumer provides a fetchSuggestions callback and optional rendering slots. The root manages all internal state — input value, suggestions, loading, error, highlighted index. This is the sweet spot: the consumer owns the data source and the UI, but the component owns the behavior.
All-in-one prop
Rigid — no API integration, no loading state. Rejected.
Fully controlled
Maximum flexibility, maximum boilerplate. Rejected.
Compound + fetchSuggestions
Consumer owns data and UI, component owns behavior. Chosen.
Key Insight
The compound pattern with a fetch callback is the same approach used by React Query's useQuery and SWR. The component says "give me a fetch function and I'll handle the rest." This inversion of control keeps the component agnostic about data sources while giving it full control over render timing.
3 · Data Model & State Shape
Six state variables drive the entire component. That is more than the dropdown menu's two, but the autocomplete has a richer interaction model — loading, error, and open/close states are all first-class concerns.
inputValue: The current text in the input. This is the seed for all queries. Controlled from the outside if the consumer passes value.
suggestions: The fetched results for the current debounced query. This is an array, not a map — we show results for exactly one query at a time.
highlightedIndex: Which suggestion is currently focused by keyboard or hover. Initialized to -1 (no selection). The GFE source emphasizes that this must be shared between mouse and keyboard interactions.
isOpen: Whether the suggestion list is visible. Derived from suggestions.length > 0 most of the time, but also controlled by focus/blur and Escape key.
isLoading: True while a fetch is in-flight. Used to show a spinner or skeleton.
error: Stores the last fetch error. Reset to null on each new fetch.
The cache (separate from state)
The cache is not React state. It is a plain LRU data structure stored in a useRef. This is deliberate: the cache should not trigger re-renders. It is a performance optimization that sits alongside the component, not inside the render cycle.
LRUCache.tstypescript
class LRUCache<T> { private cache: Map<string, T>; private maxSize: number; constructor(maxSize: number = 100) { this.cache = new Map(); this.maxSize = maxSize; } get(key: string): T | undefined { if (!this.cache.has(key)) return undefined; // Move to end (most recently used) const value = this.cache.get(key)!; this.cache.delete(key); this.cache.set(key, value); return value; } set(key: string, value: T): void { if (this.cache.has(key)) { this.cache.delete(key); } else if (this.cache.size >= this.maxSize) { // Evict least recently used (first entry) const firstKey = this.cache.keys().next().value; if (firstKey !== undefined) this.cache.delete(firstKey); } this.cache.set(key, value); } has(key: string): boolean { return this.cache.has(key); } clear(): void { this.cache.clear(); }}
The LRU cache uses JavaScript's Map insertion order. Every get() deletes and re-inserts the entry, moving it to the end. The oldest entry — the least recently used — sits at the front and is evicted when the cache exceeds maxSize.
The GFE reference discusses three cache strategies. A hash map (query → results) is simple but duplicates data across similar queries. A flat list avoids duplication but requires client-side filtering. A normalized map stores results by ID and query keys reference those IDs. I chose the hash map with LRU eviction — it is O(1) for reads and writes, and the maxSize cap prevents unbounded memory growth.
Note
I follow the principle of keeping the state surface minimal. The cache lives outside React state because it does not affect what the user sees until a fetch completes. Only truly-observable data — input value, suggestions, loading, error — belongs in useState.
4 · Interface Definition (API)
The API is the contract between the component and its consumer. Every prop has a default and a clear rationale.
types.tstypescript
interface Suggestion { id: string; label: string; description?: string; icon?: string;}interface AutocompleteProps { /** Controlled input value */ value?: string; /** Default value for uncontrolled mode */ defaultValue?: string; /** Called when input value changes */ onChange?: (value: string) => void; /** Called when user selects a suggestion */ onSelect: (suggestion: Suggestion) => void; /** URL or function that returns suggestions */ fetchSuggestions: ( query: string, signal?: AbortSignal, ) => Promise<Suggestion[]>; /** Minimum characters before fetching */ minQueryLength?: number; /** Debounce delay in ms */ debounceMs?: number; /** Number of results to show */ maxResults?: number; /** Placeholder text */ placeholder?: string; /** Custom render for each suggestion */ renderSuggestion?: (suggestion: Suggestion) => React.ReactNode; /** Custom render for the input */ renderInput?: (props: InputRenderProps) => React.ReactNode; /** Loading state indicator */ loadingIndicator?: React.ReactNode; /** Error state handler */ onError?: (error: Error) => void; /** Cache TTL in ms */ cacheTtl?: number; className?: string;}
Prop decisions
value / defaultValue: I support both controlled and uncontrolled modes. If the consumer passes value, the component is controlled and onChange is required. If only defaultValue is given, the component manages its own state. This matches the React pattern used by<input /> and <select />.
fetchSuggestions: A function that receives the query string and an AbortSignal. The consumer implements the actual HTTP call; the component passes the signal for cancellation. This keeps the component testable without a server.
minQueryLength: Defaults to 2. Typing one character produces too many irrelevant results and wastes server resources. The GFE source recommends 3 or more for production use.
debounceMs: Defaults to 300ms, the standard threshold recommended by Google's RAIL model. Shorter values feel more responsive but increase server load.
renderSuggestion: A render prop for custom suggestion UI. If omitted, the component renders a simple text label. This is the inversion-of-control pattern mentioned in the GFE source.
maxResults: Caps the displayed suggestions. Defaults to 10. Beyond this, the list becomes overwhelming for the user.
Server API contract
The server should accept the following query parameters:
q — the search query string
limit — max results per page
page — pagination offset (for infinite scroll)
The response should be a JSON array of suggestion objects, each with an id and label at minimum. The GFE source notes that pagination is "useful if there is a need to allow users to scroll down beyond the initial list."
5 · Component Deep Dive
This is where the autocomplete reveals its complexity. Let's examine each subsystem: debounce, keyboard handling, race-condition safety, and click-outside detection.
Debounce — the heartbeat of autocomplete
Without debounce, every keystroke fires an API call. A user typing "facebook" at moderate speed generates 8 requests in under a second. Most of those requests are useless — the intermediate results for "f," "fa," "fac" are never shown to the user because they are overwritten before the response arrives.
The solution is a debounce hook that delays the API call until the user stops typing:
The debounced value changes only after a pause in typing. The useEffect watches the debounced value and triggers the fetch. The cleanup function aborts the previous fetch via AbortController.
Warning
A common mistake is to debounce the fetch function itself instead of the input value. Debouncing the function means the fetch is delayed from the last call — but if the user types slowly, intermediate values get sent. Debouncing the value means only pauses trigger fetches, which is the correct behavior.
Figure 2 — Timeline of a single autocomplete interaction. The debounce timer resets on every keystroke; only after 300ms of silence does the API call fire.
Race conditions with AbortController
Even with debounce, race conditions can occur. Consider: the user types "foo," the debounce timer fires, a fetch starts for "foo." Before it completes, the user types "foot" and the debounce fires again. The response for "foo" arrives after "foot" — if we simply set state, we show results for the wrong query.
The GFE source mentions two approaches: attach a timestamp to each request and only display the latest, or save results in a map keyed by query. I use AbortController to cancel in-flight requests before starting new ones:
The abortRef holds the most recent controller. Before creating a new fetch, the handler aborts the previous one. The catch block ignores AbortError — this is not a real error, just a cancelled request. The alternative — saving every response in a map — is useful if the user might navigate back to a previous query, but for most autocomplete use cases, aborting stale requests is simpler and more memory-efficient.
Keyboard navigation
The keyboard model is simpler than the dropdown menu's because there is only one focus target — the input. Instead of moving focus between items, we use aria-activedescendant to tell the browser and screen reader which item is "focused" while the input retains actual focus.
Figure 3 — Keyboard navigation flow. Arrow keys cycle through results; Enter selects; Escape closes the list. aria-activedescendant tracks the highlighted option.
keyboardNav.tstypescript
function handleKeyDown( e: React.KeyboardEvent, items: Suggestion[], highlightedIndex: number, setHighlightedIndex: (i: number) => void, onSelect: (item: Suggestion) => void,) { switch (e.key) { case "ArrowDown": e.preventDefault(); const next = (highlightedIndex + 1) % items.length; setHighlightedIndex(next); break; case "ArrowUp": e.preventDefault(); const prev = (highlightedIndex - 1 + items.length) % items.length; setHighlightedIndex(prev); break; case "Enter": e.preventDefault(); if (highlightedIndex >= 0 && items[highlightedIndex]) { onSelect(items[highlightedIndex]); } break; case "Escape": e.preventDefault(); setIsOpen(false); setHighlightedIndex(-1); break; }}
I chose to wrap ArrowDown/ArrowUp — pressing ArrowDown on the last item jumps to the first. Some implementations stop at the ends. Wrapping is faster for the user: they never hit a dead end and have to reverse direction.
Click-outside detection
When the user clicks outside the autocomplete, the suggestion list should close. The same hook from the dropdown menu applies here, but attached to the container element:
I listen on mousedown rather than click because it fires before blur. If the user clicks a suggestion, I want the click to register before the blur handler potentially resets the state.
6 · Data Flow & Communication
Let's trace a complete interaction to see how the data flows through the component.
User types characters
Input onChange fires. inputValue updates immediately. Each keystroke resets the debounce timer.
Debounce timer expires (300ms)
The debounced value changes. The effect starts a new fetch with AbortController. Previous in-flight request is aborted.
Cache lookup
Before calling fetchSuggestions, the controller checks the LRU cache. If found, return cached data instantly — skip the network call.
API call (if cache miss)
fetchSuggestions(query, signal) is called. isLoading → true. The consumer's function hits the server.
Response arrives → render suggestions
suggestions state updates with results. isLoading → false. isOpen → true. The ResultsList renders below the input.
User navigates with keyboard
ArrowDown/ArrowUp updates highlightedIndex. aria-activedescendant attribute updates on the input. The highlighted item scrolls into view if needed.
User selects a suggestion
Enter or click triggers onSelect(suggestion). inputValue updates to the selected label. isOpen → false. highlightedIndex resets to -1.
Notice how the cache intercepts the flow before the network call. This is important: if the user types "foo," deletes the last character to get "fo," and retypes "foo," the second fetch hits the cache and resolves instantly. The user sees no loading state at all.
7 · Performance Optimization
Autocomplete is a performance-sensitive component because every keystroke triggers a cascade of events. Here are the optimizations I consider essential.
LRU cache with bounded size
The LRU cache prevents redundant network calls. When the user types a query that has been seen before, the cache returns results in O(1) time with zero network latency. The maxSize cap (default 100 entries) prevents memory leaks on long-lived pages. The GFE source specifically recommends this for "long-lived single page applications."
AbortController for stale requests
Every new fetch aborts the previous one. This prevents wasted bandwidth and CPU processing for responses that will never be shown. The pattern is simple: store the controller in a ref, abort before creating a new fetch.
Virtualization for large suggestion lists
Most autocomplete results are under 10 items, but some use cases — like GitHub's repository picker — can return hundreds. Rendering hundreds of DOM nodes inside a popup will cause jank. The solution is virtualize the list using react-window or a custom virtual scroller. Only render the items that are visible in the scroll viewport; the rest are placeholders that contribute to the scroll height.
The GFE source cites the web.dev article on list virtualization: "The number of elements rendered at first is a very small subset of the entire list and the 'window' of visible content moves when the user scrolls."
Memoizing suggestion rendering
Each keystroke produces a new array of suggestions. If the consumer's renderSuggestion creates new React elements, every item re-renders on every fetch. Wrap each result item in React.memo and memoize the rendered list with useMemo keyed on the suggestions reference.
Tradeoff table
Strategy
Pros
Cons
Hash map cache
O(1) lookup, simple to implement
Duplicate data, unbounded growth without eviction
LRU cache (chosen)
O(1) lookup, bounded memory, evicts stale entries
Slightly more code than hash map
Normalized cache
No data duplication, efficient memory usage
Complex preprocessing on each read
Debounce value vs function
Debouncing value catches all pauses correctly
Slightly more state management
Virtualized list
Constant DOM nodes regardless of result count
Extra dependency, coordinate scroll state
8 · Security Considerations
Autocomplete has a larger security surface than most UI components because it displays server-provided text inside the page.
XSS via suggestion labels: Suggestion text comes from the server. If the server is compromised or returns unsanitized data, an attacker could inject script tags. Since React escapes JSX by default, this is safe as long as the consumer does not use dangerouslySetInnerHTML. I explicitly omit that prop from the API.
Rate limiting the fetchSuggestions call: The debounce already limits how often fetchSuggestions is called, but a malicious user can programmatically call it faster. The consumer should implement server-side rate limiting and expose it via HTTP 429 responses. The component should handle 429 gracefully by showing an error state and retrying with backoff.
Data exposure through timing: If the autocomplete fires requests for every keystroke without minQueryLength, a slow attacker could infer database contents through timing side channels. The minQueryLength default of 2 mitigates this partially. For sensitive search endpoints, the consumer should rate-limit on the server side.
Autofill interference: Browser autofill can inject values into the input that trigger unwanted API calls. The debounce prevents rapid-fire requests, but the component should also check that the input change was user-initiated using isTrusted on the event.
Warning
The fetchSuggestions prop receives the user's raw input text. If the consumer concatenates it directly into a URL without encoding, they open themselves to injection attacks. Document this clearly: always use encodeURIComponent when building query URLs.
9 · Testing Strategy
I test autocomplete with React Testing Library and user-event. The key principle: test behavior, not implementation. Mock the fetch function, type into the input, and assert on what appears in the DOM.
Suggestions appear after debounce: Type a query, wait for the debounce, verify that role="listbox" appears with correct number of options. This tests the entire fetch → render pipeline.
Keyboard navigation highlights items: Press ArrowDown and verify that the first option has aria-selected="true". Press again and verify the second is selected. Test wrapping behavior.
Escape closes the list: Open the list, press Escape, verify role="listbox" is removed from the DOM.
Click selects and closes: Click a suggestion, verify onSelect was called with the correct item, and the list closes.
Click outside closes: Open the list, click outside the component, verify the list disappears.
Minimum query length respected: Type fewer characters than minQueryLength and verify that fetchSuggestions was never called.
Race condition: slow response ignored: Mock two fetches where the first resolves after the second. Verify that the displayed results match the later (second) query, not the earlier one.
Cache returns cached data without fetch: Type a query, wait for results, type it again, verify that fetchSuggestions was called exactly once (the second call hit the cache).
Note
For the race-condition test, use jest.useFakeTimers() with delays applied to each response. This gives you precise control over the order of resolution. Without fake timers, the test becomes flaky due to unpredictable async timing.
10 · Accessibility
Accessibility is where most autocomplete implementations fail. The WAI-ARIA 1.2 Combobox pattern is one of the most complex ARIA patterns, and getting it wrong means screen reader users cannot use the component at all.
The ARIA combobox pattern
ARIA 1.2 defines three roles that work together:
combobox on the container element (a <div> wrapping the input). This has aria-expanded (true when the list is visible), aria-haspopup="listbox", and aria-controls pointing to the listbox id.
listbox on the suggestions <ul>. This has aria-labelledby referencing the input's label.
option on each <li>. The highlighted option has aria-selected="true". All others have aria-selected="false" or omit the attribute.
aria-activedescendant
This is the key difference from a dropdown menu. In a combobox, focus stays on the input at all times. The aria-activedescendant attribute on the input points to the id of the currently highlighted option. The screen reader announces the option's text as if focus were on it, even though actual focus remains on the input.
The attribute updates as the user presses ArrowDown/ArrowUp:
When the suggestion list appears, the screen reader should announce something like "3 suggestions available." This is achieved with a aria-live="polite" region that updates whenever the suggestion count changes. No JavaScript Speech API needed — the live region is a standard ARIA technique.
Focus management
When the input is focused, the list should appear (if there are suggestions). When the input loses focus (blur), the list should close. However, clicking a suggestion triggers a blur before the click event. I use a short timeout in the blur handler to allow the click to propagate: if the click happens within 150ms of blur, don't close the list. This is a common pattern in Radix UI and React Aria.
i18n and RTL
The component respects the inherited dir attribute. In RTL mode, the suggestion list aligns to the right of the input. All ARIA attributes are language-agnostic, so no changes are needed for screen reader support in different languages.
Key Insight
The aria-activedescendant pattern simplifies focus management compared to the dropdown menu. In a dropdown, each item is a focusable element and ArrowDown moves DOM focus. In an autocomplete, the input keeps focus and only the ARIA attribute changes. This means no focus trap, no Tab key issues, and no edge cases with shift-tabbing out of the component.
11 · Live Demo
Try the full implementation in a WebContainer playground. You can edit the code and see changes instantly — experiment with different debounce values, custom renderers, and keyboard behavior.
Editable example loads when this section enters view.
Try these interactions: type a query and wait for suggestions, press ArrowDown/ArrowUp to cycle, press Enter to select, press Escape to dismiss, and click outside to close the list.
12 · Key Takeaways
Debounce the value, not the function. A debounce hook that delays the value change is simpler and more correct than debouncing the fetch function. The cleanup effect naturally aborts stale requests.
AbortController solves race conditions. Every new fetch cancels the previous one. This is cleaner than tracking timestamps or building a response map, and it frees network resources on the client.
LRU cache with bounded size. A Map-based LRU cache provides O(1) lookups, automatic eviction, and zero extra dependencies. Without a size cap, the cache grows unbounded on long-lived pages.
aria-activedescendant keeps focus on the input. Unlike a dropdown menu where focus moves between items, the autocomplete input retains focus. The ARIA attribute tells screen readers which option is highlighted without moving DOM focus.
Compound API with fetchSuggestions is the sweet spot. The consumer owns data and UI; the component owns behavior. This pattern is flexible enough for Google's search bar and simple enough for a country picker.
minQueryLength is a performance and security feature. It reduces server load, avoids showing irrelevant results, and mitigates timing-based data exfiltration attacks.
The autocomplete looks like a text box with a dropdown. It isn't. The version we just designed handles debounce, race conditions, caching, keyboard navigation, ARIA compliance, click-outside detection, and custom rendering — and the core logic fits in a few hundred lines. That's the signature of a well-scoped component: it does one thing (suggest completions) and does it completely.