Build a React Autocomplete Component with Async Search
System DesignModel answerLast updated
Create a reusable autocomplete input component in React that queries a search API, handles asynchronous responses, and displays suggestions efficiently.
You're building a reusable autocomplete component for a React application. The component should provide a text input that displays matching suggestions in a dropdown as users type, allowing them to select from the results. A backend search endpoint is already available for fetching suggestions.
Your task is to design this component thoughtfully, addressing:
-
API Contract: Define how your component will communicate with the search endpoint—what parameters to send, what response format to expect, how to handle pagination, and how to deal with network issues.
-
Component Structure: Break down the autocomplete into logical sub-components. Explain how state flows between them, where rendering happens, and why certain architectural choices (like portals) matter.
-
Request Optimization: Decide between throttling and debouncing to reduce unnecessary API calls. Justify your choice and explain how it integrates with other request management concerns.
-
Client-Side Caching: Design a caching strategy to improve performance and reduce server load. Consider different approaches for storing and retrieving results, and explain when each strategy helps.
-
Public Interface: Define what props your component exposes and what gets exported to consuming teams versus what stays internal.
Throughout your design, consider accessibility requirements, edge cases around network timing, and the trade-offs between flexibility and simplicity.
Clarifying Questions to Consider
- What type of data is being searched? Do results need custom rendering beyond simple text?
- Should users be able to select multiple items, or enter text that doesn't match any suggestion?
- What is the typical result volume and API response time?
- Where in the application will this component be used? (dialogs, scrolling containers, etc.)
- What are the browser support and accessibility requirements?
Hints
Hint 1
Think about race conditions when multiple requests are in flight—how do you ensure the displayed results match the current input?
Hint 2
Portals solve specific rendering problems with z-index and overflow clipping. What scenarios require them?
Hint 3
Caching by exact query string is straightforward, but how can you leverage partial matches to improve the hit rate?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution Approach
1. API Contract Design
The component needs a clean contract with the backend. The request should include:
query: the search term (string)limit: maximum results to return (e.g., 10)offset: for pagination if needed (default 0)
The response structure:
{
"results": [
{ "id": "unique-id", "text": "Display text", "metadata": {...} }
],
"total": 150,
"hasMore": true
}
Key considerations:
- Cap the limit server-side (e.g., max 50) to prevent abuse
- Return results with stable IDs for React keys
- Include metadata that might be needed for rendering or selection
- Handle out-of-order responses by tracking a request ID or timestamp and ignoring stale responses
- Implement error responses with clear status codes (429 for rate limiting, 400 for invalid queries)
The component should cancel in-flight requests when new queries are issued using AbortController.
2. Component Architecture
Break the autocomplete into focused pieces:
AutocompleteInput (main component): Manages state—current input value, suggestion list, selected index, loading state, and open/closed status. Coordinates between child components.
TextInput: Renders the actual input field. Handles keyboard events (arrow keys, enter, escape) and forwards them to the parent. Manages focus and ARIA attributes (aria-expanded, aria-controls, aria-activedescendant).
SuggestionList: Receives suggestions array and selected index, renders items with proper highlighting. Handles mouse events for selection and hover.
Portal & PositionManager: The dropdown renders through a portal to the document body to escape overflow:hidden containers and avoid z-index battles. The position manager calculates coordinates relative to the input, handles viewport boundaries, and updates on scroll/resize. If multiple autocompletes exist, a portal manager tracks the stack for proper dismissal order.
State flow: Input value lives in AutocompleteInput (controlled or uncontrolled). Keyboard navigation updates selectedIndex. Click/enter triggers onSelect callback. The portal receives position coordinates as props and renders at those absolute coordinates.
Accessibility: Use the combobox pattern—role="combobox" on the input, role="listbox" on the dropdown, role="option" on items. Connect them with aria-controls and aria-owns. Announce loading states and result counts to screen readers using aria-live regions.
3. Debouncing vs Throttling
Throttling fires requests at regular intervals (e.g., every 300ms) while typing continues. Debouncing waits for a pause in typing (e.g., 300ms of inactivity) before firing.
Choice: Debouncing is better for autocomplete because:
- Avoids wasting requests on partial queries the user is still typing through
- Reduces server load significantly (one request per typing pause vs. one per interval)
- Natural fit with user behavior—users typically pause briefly when they've typed enough
Trade-off: Debouncing can feel slightly less responsive than throttling if users type slowly. Mitigate by keeping the delay short (200-300ms).
Integration with other optimizations:
- Skip requests if query is below minimum length (e.g., 2 characters)
- Cancel previous requests with AbortController when a new one starts
- Don't debounce cache hits—show cached results immediately
- Reset the debounce timer on every keystroke
4. Client-Side Caching Strategy
Combine three complementary approaches:
LRU Cache by normalized query:
- Store results keyed by lowercased, trimmed query
- Capacity of 50-100 entries with TTL of 5-10 minutes
- Simple to implement, provides exact-match hits
- Works well for repeated searches (user backspaces then retypes)
Prefix matching:
- When querying "javascript", check if "java" or "javascr" are cached
- If "java" is cached and has more results than the limit, reuse those results immediately while fetching fresh ones in the background
- Only works when typing forward, not useful for edits in the middle
- Risks showing stale results if new matches appear for longer queries
Popular/recent results for short queries:
- Pre-populate or cache results for empty string or single characters
- Show these as "trending" or "recent searches" for quick starts
- Helps when users are exploring rather than searching for something specific
Combining strategies:
- Check exact match cache first—instant return if hit
- Check prefix cache for longer queries—show while fetching
- For empty or very short input, show popular results
- After API response, update the exact-match cache
Pitfalls: Prefix matching can show outdated results if data changes. Mitigate by always fetching fresh results in the background and replacing prefix-cached results when they arrive.
5. Public Interface
Exported component:
<Autocomplete
// Data source
fetchSuggestions={(query) => Promise<Suggestion[]>}
// State control
value={value}
defaultValue=""
onChange={(value) => {}}
onSelect={(item) => {}}
// Behavior
minQueryLength={2}
debounceMs={300}
maxResults={10}
// Rendering
renderSuggestion={(item) => ReactNode}
placeholder="Search..."
// Accessibility
inputProps={{ 'aria-label': 'Search' }}
/>
What to export:
- Main
Autocompletecomponent only - Optionally:
useAutocompletehook for headless implementations - Types:
Suggestion,AutocompleteProps
Keep internal: Portal implementation, position calculations, cache utilities, suggestion list rendering. This allows refactoring without breaking consumers.
Design principles:
- Support both controlled (value prop) and uncontrolled (defaultValue) modes
- Provide sensible defaults (debounce 300ms, min length 2)
- Allow render prop customization without requiring it
- Make fetchSuggestions the only required prop—keep the API minimal
- Ensure the component is testable by allowing mock implementations of fetchSuggestions
Complexity & Performance
- Debouncing reduces API calls to O(pauses) instead of O(keystrokes)
- LRU cache provides O(1) lookups with bounded memory
- Portal rendering is O(1) per update
- Keyboard navigation through N results is O(N) per keystroke
A well-implemented autocomplete should handle hundreds of keystrokes and thousands of cached entries without performance degradation.