Autocomplete Input with Hand-Rolled Debounce
System DesignModel answerLast updated
Build a search input that fetches and displays suggestions as the user types, using a debounce you write yourself and handling stale responses, keyboard navigation, and cleanup.
Autocomplete Input with Hand-Rolled Debounce
You are building a text input that displays a dropdown of suggestions as the user types. Suggestions come from an async lookup function — do not import a debounce utility (lodash, etc.); write that logic yourself.
The lookup function has this shape:
declare function getSuggestions(query: string, signal?: AbortSignal): Promise<string[]>;
The component should:
- Call
getSuggestionsonly after the user has paused typing for a short delay (debounce), not on every keystroke - Show a list of suggestions below the input while results are loading or available
- Let the user pick a suggestion with the mouse or keyboard
- Clear the list when the input is emptied
- Avoid showing results from an earlier query if a newer one finishes first
What to address
- Debounce implementation — write a debounce function from scratch and explain how it behaves when the component re-renders
- Stale response handling — explain how you prevent an out-of-order response from overwriting fresher results
- States — loading, empty results, error, and cleared input
- Keyboard navigation — arrow keys to move through the list, Enter to confirm, Escape to dismiss
- Accessibility — how a screen reader understands the suggestion list
- Cleanup — timers and in-flight requests when the component unmounts
- Bonus — caching results for queries already seen, and how you would test timer behaviour without real delays
You may use any framework you are comfortable with, or plain DOM APIs. Explain your choices as you go.
Hints
Hint 1
A debounce function returns a new function that resets a setTimeout each time it is called; only when the timeout fires without being reset does it invoke the original function. Think about where you store that timer ID so it survives re-renders without being recreated every render cycle.
Hint 2
An AbortController lets you cancel a fetch that is already in flight. Create a new one each time a request goes out, and call abort() on the previous one before starting the next. This handles both the stale-response problem and cleanup on unmount with a single mechanism.
Hint 3
The ARIA pattern for a combobox uses role='combobox' on the input with aria-expanded and aria-controls pointing to the listbox, and role='option' on each item. aria-activedescendant tracks the keyboard-focused item without moving real focus away from the input.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
There are four interlocking concerns: the debounce timer, stale-response cancellation, UI state, and accessibility. Solve them in that order.
1. Writing the debounce
A debounce function wraps another function and delays its execution. Each new call clears the pending timer and starts a fresh one. Only the call that survives the full delay actually runs.
function debounce<T extends unknown[]>(
fn: (...args: T) => void,
delay: number
): (...args: T) => void {
let timerId: ReturnType<typeof setTimeout> | null = null;
return (...args: T) => {
if (timerId !== null) clearTimeout(timerId);
timerId = setTimeout(() => {
timerId = null;
fn(...args);
}, delay);
};
}
The re-render trap. If you call debounce(fetchFn, 300) inside a React render function body, every render creates a new debounced function with its own fresh timer, so the delay never accumulates. Store the debounced function in a ref (useRef) so the same instance persists across renders.
const debouncedFetch = useRef(
debounce((query: string) => { /* ... */ }, 300)
).current;
A 300 ms delay is a common starting point. Some teams skip the request entirely for queries shorter than two characters to avoid noisy results.
2. Cancelling stale requests
When the user keeps typing, multiple requests may be in flight simultaneously. The last one to resolve wins by default — which may not be the last one sent. Two strategies work here:
AbortController (preferred). Pass a signal to the fetch, and abort the previous request before issuing the next one. This actually stops the network work, not just the result handling.
const abortRef = useRef<AbortController | null>(null);
function fetchAndUpdate(query: string) {
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
setLoading(true);
getSuggestions(query, controller.signal)
.then(results => {
if (!controller.signal.aborted) {
setSuggestions(results);
setError(null);
}
})
.catch(err => {
if (err.name !== 'AbortError') setError('Could not load suggestions.');
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
}
On unmount, call abortRef.current?.abort() inside the useEffect cleanup to cancel any pending request.
Generation counter (alternative). Increment a counter on each request; only apply results when the resolved counter matches the current one. This is simpler but does not save network bandwidth.
3. UI states
| State | What to show |
|---|---|
| Input empty | Hide the dropdown entirely |
| Loading | Spinner or "Loading…" inside the dropdown |
| Results returned | The suggestion list |
| Empty results | "No suggestions" message |
| Error | Short error message; keep the input functional |
Clearing the input should immediately hide the dropdown and cancel any pending timer and request.
4. Keyboard navigation
Keep real focus on the <input> at all times. Use aria-activedescendant to point at the visually highlighted item without moving focus.
- ArrowDown / ArrowUp — move the highlighted index through the list, wrapping at the ends
- Enter — confirm the highlighted item, or submit if nothing is highlighted
- Escape — close the dropdown, leave the typed text as-is
function handleKeyDown(e: React.KeyboardEvent) {
if (e.key === 'ArrowDown') {
setHighlighted(i => Math.min(i + 1, suggestions.length - 1));
} else if (e.key === 'ArrowUp') {
setHighlighted(i => Math.max(i - 1, 0));
} else if (e.key === 'Enter' && highlighted >= 0) {
selectSuggestion(suggestions[highlighted]);
} else if (e.key === 'Escape') {
setSuggestions([]);
}
}
5. Accessibility
The ARIA combobox pattern covers this use case directly:
<input
role="combobox"
aria-expanded={suggestions.length > 0}
aria-controls="suggestions-list"
aria-activedescendant={highlighted >= 0 ? `suggestion-${highlighted}` : undefined}
aria-autocomplete="list"
/>
<ul role="listbox" id="suggestions-list">
{suggestions.map((s, i) => (
<li
key={s}
id={`suggestion-${i}`}
role="option"
aria-selected={i === highlighted}
>
{s}
</li>
))}
</ul>
Screen readers announce the list size and the currently highlighted item without focus ever leaving the input.
6. Caching (bonus)
A simple Map<string, string[]> keyed by query string works well. Before issuing a request, check the cache; on success, write to it. For most autocomplete use cases a plain in-memory cache is enough — no expiry needed in a single session. If you want to share it across instances, lift the cache into a module-level variable or a context.
7. Testing with fake timers
Use jest.useFakeTimers() (or the equivalent in Vitest). After simulating keystrokes, advance the clock with jest.advanceTimersByTime(300) to trigger the debounce, then resolve the mocked fetch promise. This lets you verify that:
- Rapid typing causes only one request
- An aborted request does not update state
- Cleanup on unmount does not cause state-update-after-unmount warnings
Common mistakes
- Recreating the debounced function on every render, which resets the timer each time
- Checking
signal.abortedbut still callingsetStatewhen it is true - Moving DOM focus into the list on arrow key press, making it hard for the user to keep typing
- Forgetting to cancel the timer and in-flight request in the
useEffectcleanup