Building a Scalable Combobox Component
System DesignModel answerLast updated
Architect a flexible, accessible dropdown component supporting various selection modes, data sources, and rendering up to 10,000 items efficiently.
Context
You need to create a shared combobox component for a large web application. The component will be used across many product surfaces with varying requirements: simple option pickers with a handful of static choices, searchable lists with remote data, and multi-select interfaces with thousands of items.
Your task is to design the architecture for this reusable component.
Requirements
Core Functionality
- Selection patterns: Single-select and multi-select modes
- Data handling: Both static arrays and async data with search filtering, debouncing, and pagination
- Customization: Allow custom trigger buttons, item renderers, and empty/loading states
- Control patterns: Support controlled (external state) and uncontrolled (internal state) usage
Quality Attributes
- Accessibility: Implement W3C WAI-ARIA patterns correctly with full keyboard navigation (arrow keys, Enter, Escape, Home, End, and typeahead) plus screen reader compatibility
- Performance: Maintain 60 FPS when rendering and scrolling through lists with 10,000+ items
- Maintainability: Minimize unnecessary re-renders and keep the implementation modular
Deliverables
Design and explain:
-
Public API: Propose the component interface—compound components, configuration props, or both. Justify your choice and show example usage in TypeScript or similar.
-
State Architecture: Describe the internal state machine, including open/closed status, keyboard focus tracking, and selected values. Cover how you handle outside clicks, trigger interactions, and keyboard events.
-
Accessibility Implementation: Specify the DOM structure, ARIA roles and attributes needed, and how keyboard navigation works.
-
Performance Strategy: Explain your approach to efficiently rendering large lists and handling viewport positioning.
Hints
Hint 1
Consider whether compound components or configuration props offer better extensibility for diverse use cases
Hint 2
Think about why virtualizing the list matters when rendering thousands of items—what's the actual DOM cost?
Hint 3
ARIA's aria-activedescendant pattern keeps focus on the input while visually highlighting options
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
1. Scope and Constraints Analysis
First, clarify the requirements:
- Two primary modes: A button-triggered selector (like a sort dropdown) and a text-input-based searchable picker (like autocomplete)
- Dataset scale: Up to 10,000 items means we cannot render all options in the DOM simultaneously
- At 40px per item, that's 400,000px of content
- A typical viewport shows ~8-10 items
- With reasonable overscan, we need ~20-25 DOM nodes active at once
- Frame budget: 60 FPS requires operations under 16ms
- Accessibility targets: Support NVDA, JAWS, and VoiceOver
- Explicitly out of scope: Native
<select>progressive enhancement and nested menu hierarchies (which use different ARIA patterns)
2. API Design Approach
Recommendation: Tiered architecture with three levels
Level 1: Headless hook - Pure logic with no rendering
const combobox = useCombobox({
items,
value,
onChange,
mode: 'single' | 'multiple',
isOpen,
onOpenChange
});
Level 2: Composable primitives - Maximum flexibility
<Combobox value={selected} onChange={setSelected} mode="multiple">
<ComboboxTrigger>
<button>{selected.length} selected</button>
</ComboboxTrigger>
<ComboboxContent>
<ComboboxList items={items}>
{(item, { isHighlighted, isSelected }) => (
<ComboboxOption key={item.id} value={item}>
<span>{item.label}</span>
</ComboboxOption>
)}
</ComboboxList>
</ComboboxContent>
</Combobox>
Level 3: Convenience wrapper - Common cases made simple
<Select
options={items}
value={value}
onChange={onChange}
getLabel={item => item.name}
/>
Why compound components?
| Approach | Advantages | Drawbacks |
|---|---|---|
| Config props only | Simpler API, easier to learn | Prop explosion for customization, rigid layout |
| Compound components | Natural composition, flexible layouts | Steeper learning curve, complex typing |
Compound components win for a shared library because they scale to diverse requirements without bloating the API surface.
3. State Management
Core state structure:
type State = {
phase: 'closed' | 'open' | 'loading' | 'error',
highlightedKey: Key | null, // Use keys, not indices (data can change)
selectedMap: Map<Key, Item>,
searchQuery: string,
itemsPage: Item[],
nextCursor: string | null,
hasMore: boolean
}
Critical state transitions:
- Opening: Highlight the first selected item, or first available item if none selected
- Selection in single mode: Select the item and immediately close
- Selection in multi mode: Toggle selection state, remain open
- Outside clicks: Attach a global
pointerdownlistener only while open, check if the click target is within trigger or popover refs (usecomposedPath()for portal support) - Focus management: Keep DOM focus on the trigger/input element always; use
aria-activedescendantto indicate which option is "active"
Why aria-activedescendant instead of moving focus?
- Preserves caret position during search
- Eliminates focus thrashing
- Works seamlessly with virtualization (focused element might not exist in DOM)
Async data flow:
User types → debounce 250ms → cancel previous request →
fetch with AbortSignal → tag with requestId →
on response, verify requestId matches latest → update state
Cache responses by (query, cursor) pairs to avoid redundant fetches.
Preventing unnecessary re-renders:
- Store state in a subscription-based store (similar to Zustand)
- Each option subscribes only to
isHighlighted(key)andisSelected(key)selectors - Changing highlight re-renders exactly 2 rows, not the entire list
4. Accessibility Implementation
DOM structure for text-input combobox:
<div>
<input
role="combobox"
aria-expanded="true"
aria-controls="listbox-id"
aria-activedescendant="option-5"
aria-autocomplete="list"
/>
<div role="listbox" id="listbox-id">
<div role="option" id="option-5" aria-selected="true" aria-posinset="5" aria-setsize="156">
Item 5
</div>
<!-- ... -->
</div>
</div>
For button-triggered mode:
- Trigger becomes
<button role="combobox">instead of input - Remove
aria-autocomplete
Key ARIA attributes:
aria-activedescendant: Points to the currently highlighted option's IDaria-posinsetandaria-setsize: Required when virtualizing—screen readers can't infer "item 5 of 200" when only 20 DOM nodes existaria-selected: Marks selected itemsaria-disabled: For disabled options
Keyboard navigation:
- Arrow Up/Down: Navigate through options, wrap at boundaries
- Home/End: Jump to first/last option
- Enter: Confirm selection of highlighted item
- Escape: Close popover (first press), clear input (second press)
- Tab: Close popover and commit selection (in select mode)
- Typeahead: Buffer characters for 500ms, search against full dataset (not just visible DOM)
Live announcements:
<div role="status" aria-live="polite" aria-atomic="true">
45 results available
</div>
Debounce announcements to avoid spamming during rapid changes.
5. Performance Optimization
Virtualization strategy:
Use windowed rendering with fixed-height rows by default:
- Only render visible rows + overscan buffer (~5 above and below viewport)
- Compute scroll offset using:
offset = rowHeight × startIndex - Time complexity: O(1) for scroll position calculations
For variable-height rows:
- Measure each rendered row with
ResizeObserver - Cache measurements in prefix-sum array for O(log n) binary search
- Trade memory for speed
Critical optimization: Pin the highlighted row
Even if scrolled out of view, always render the highlighted option so aria-activedescendant references a real DOM node. Screen readers fail silently if the referenced node doesn't exist.
Scroll synchronization:
When keyboard navigates, call scrollIntoView before updating aria-activedescendant so the screen reader finds the node already on screen.
Local filtering performance: For 10,000 static items:
- Pre-process labels to lowercase once
- Use simple
includes()check—runs in ~2ms on modern hardware - Wrap UI update in
startTransitionto keep input responsive
Intersection-based infinite scroll:
Use IntersectionObserver on a sentinel element at list end. When it becomes visible and hasMore === true, fetch the next page.
6. Key Trade-offs
aria-activedescendant vs roving tabindex:
- Roving: Better for static menus, gives real focus
- activedescendant: Required for editable comboboxes, survives virtualization
- Choice: Use activedescendant for consistency across both modes
Controlled vs uncontrolled:
Provide both patterns via a useControllableState hook. Detect the initial mode (presence of value prop) and warn if it changes during the component's lifecycle.
Portal vs inline rendering:
Portal the popover to document.body to escape overflow/z-index containers, but adds complexity to outside-click detection (must use refs, not DOM ancestry).
Fixed vs dynamic height: Fixed-height is simpler and more performant; offer dynamic-height as opt-in for cases where content varies significantly.
Common Mistakes to Avoid
- Rendering all 10,000 items and hiding with CSS (causes ~500ms layout cost)
- Using array indices as keys when data can be filtered/sorted
- Moving DOM focus to options (breaks typeahead in input)
- Forgetting
aria-setsizewhen virtualizing - Synchronous filtering that blocks the main thread
- Not canceling in-flight requests when query changes
This architecture balances flexibility, performance, and accessibility while remaining maintainable for a team building on top of it.