Tech Interview RoomStudy guides

Frontend Coding

Machine coding: build an accessible autocomplete (typeahead) in React.

Advanced · 2 min read · Lesson 10 of 10 in Frontend Coding

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

  1. Debounced requests (300 ms) and a minimum query length.
  2. 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.
  3. Caching previous queries in a Map so backspacing is instant.
  4. Keyboard: ArrowDown/ArrowUp move the active option, Enter selects, Escape closes.
  5. Accessibility: the WAI-ARIA combobox pattern: role="combobox", aria-expanded, aria-controls, aria-activedescendant on the input; role="listbox" and role="option" with aria-selected on the list. Focus stays in the input.
  6. Highlight the matched text, close on outside click, and clean up on unmount.
  7. Clear component structure and state, ideally with a custom hook for data.
jsx
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:

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