Machine coding: build an accessible autocomplete (typeahead) in React.
Requirements usually given
Fetch suggestions as the user types, show them in a dropdown, choose with mouse or keyboard, and handle loading, empty and error states. Time box: 45 to 60 minutes.
What interviewers evaluate
- Debounced requests (300 ms) and a minimum query length.
- Race conditions: a slow response for "re" must not overwrite results for "react". Abort the previous request with
AbortController, or ignore responses whose query is stale. - Caching previous queries in a
Mapso backspacing is instant. - Keyboard: ArrowDown/ArrowUp move the active option, Enter selects, Escape closes.
- Accessibility: the WAI-ARIA combobox pattern:
role="combobox",aria-expanded,aria-controls,aria-activedescendanton the input;role="listbox"androle="option"witharia-selectedon the list. Focus stays in the input. - Highlight the matched text, close on outside click, and clean up on unmount.
- Clear component structure and state, ideally with a custom hook for data.
import { useEffect, useId, useRef, useState } from 'react';
function useSuggestions(query, fetcher, delay = 300) {
const [state, setState] = useState({ status: 'idle', items: [] });
const cache = useRef(new Map());
useEffect(() => {
const q = query.trim();
if (q.length < 2) { setState({ status: 'idle', items: [] }); return; }
if (cache.current.has(q)) { setState({ status: 'success', items: cache.current.get(q) }); return; }
const controller = new AbortController();
const timer = setTimeout(async () => {
setState(s => ({ ...s, status: 'loading' }));
try {
const items = await fetcher(q, controller.signal);
cache.current.set(q, items);
setState({ status: 'success', items });
} catch (e) {
if (e.name !== 'AbortError') setState({ status: 'error', items: [] });
}
}, delay);
return () => { clearTimeout(timer); controller.abort(); }; // debounce + no stale responses
}, [query, fetcher, delay]);
return state;
}
function Highlight({ text, query }) {
const i = text.toLowerCase().indexOf(query.toLowerCase());
if (i < 0 || !query) return text;
return <>{text.slice(0, i)}<mark>{text.slice(i, i + query.length)}</mark>{text.slice(i + query.length)}</>;
}
export function Autocomplete({ label, fetcher, onSelect }) {
const [query, setQuery] = useState('');
const [open, setOpen] = useState(false);
const [active, setActive] = useState(-1);
const { status, items } = useSuggestions(query, fetcher);
const listId = useId();
const rootRef = useRef(null);
useEffect(() => {
const onDown = e => { if (!rootRef.current?.contains(e.target)) setOpen(false); };
document.addEventListener('pointerdown', onDown);
return () => document.removeEventListener('pointerdown', onDown);
}, []);
function choose(item) {
setQuery(item.label);
setOpen(false);
setActive(-1);
onSelect(item);
}
function onKeyDown(e) {
if (e.key === 'ArrowDown') { e.preventDefault(); setOpen(true); setActive(a => Math.min(a + 1, items.length - 1)); }
else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(a - 1, 0)); }
else if (e.key === 'Enter' && open && active >= 0) { e.preventDefault(); choose(items[active]); }
else if (e.key === 'Escape') setOpen(false);
}
const showList = open && query.trim().length >= 2;
return (
<div ref={rootRef} className="autocomplete">
<label htmlFor={`${listId}-input`}>{label}</label>
<input
id={`${listId}-input`}
role="combobox"
aria-autocomplete="list"
aria-expanded={showList}
aria-controls={listId}
aria-activedescendant={active >= 0 ? `${listId}-${active}` : undefined}
value={query}
onChange={e => { setQuery(e.target.value); setOpen(true); setActive(-1); }}
onKeyDown={onKeyDown}
onFocus={() => setOpen(true)}
autoComplete="off"
/>
{showList && (
<ul id={listId} role="listbox">
{status === 'loading' && <li aria-live="polite">Searching…</li>}
{status === 'error' && <li role="alert">Could not load suggestions</li>}
{status === 'success' && items.length === 0 && <li>No results</li>}
{items.map((item, i) => (
<li
key={item.id}
id={`${listId}-${i}`}
role="option"
aria-selected={i === active}
onPointerDown={e => e.preventDefault()} // keep focus in the input
onClick={() => choose(item)}
onMouseEnter={() => setActive(i)}
>
<Highlight text={item.label} query={query.trim()} />
</li>
))}
</ul>
)}
</div>
);
}Example
Using it with a real API; the fetcher is defined outside the component so it is stable and does not retrigger the effect:
const searchCities = async (q, signal) => {
const res = await fetch(`/api/cities?q=${encodeURIComponent(q)}`, { signal });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).map(c => ({ id: c.id, label: `${c.name}, ${c.country}` }));
};
export default function App() {
const [city, setCity] = useState(null);
return (
<>
<Autocomplete label="City" fetcher={searchCities} onSelect={setCity} />
{city && <p>Selected: {city.label}</p>}
</>
);
}encodeURIComponent matters: without it, a query containing & or # would break the URL.
Follow-up questions interviewers ask
Try answering each one before you open it.
How would you test this component?
With React Testing Library and fake timers: type into getByRole('combobox'), advance timers by 300 ms, mock the fetcher (or MSW) to return results, assert getAllByRole('option'), press ArrowDown and Enter with user-event, and check onSelect was called. Add a race test: resolve the first request after the second and assert that the newer results are shown.