KatInterview

Build a React Autocomplete Component with Async Search

System DesignModel answer
MediumModel answerSystem Designreactcomponent-designapi-integration

Last 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:

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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?