Lesson 188 of 296
Designs: autocomplete, infinite scroll, data table
What you will learn
- Designing an autocomplete (typeahead) component
- Designing an infinite scrolling feed
- Designing a data table with sorting, filtering and pagination
- The key trade-offs in each
On this page
Design 1: Autocomplete
The question: "Design a search box that shows suggestions as the user types", like Google search or a city picker.
Requirements to clarify: where suggestions come from (server or a local list); how many results; minimum characters before searching; should it show recent searches; selection by mouse and keyboard; mobile support.
Architecture:
<Autocomplete>
<input> the text field
<ul role="listbox"> the suggestion list
<li role="option">State: query, results, status (idle, loading, error, success), isOpen, activeIndex (the highlighted option).
API: GET /api/search?q=lon&limit=8 returns [{ id, label }].
Key techniques:
| Problem | Solution |
|---|---|
| A request on every keystroke | Debounce the query (about 300 ms) and require a minimum length (2 to 3 characters) |
| Old responses arriving after new ones (race condition) | Abort the previous request with AbortController, or ignore responses that are not for the latest query |
| The same queries repeated | Cache results by query in a Map (with a size limit) |
| Slow server | Show a loading indicator; keep the previous results visible meanwhile |
| Highlighting | Bold the part of each suggestion that matches the query, using text nodes, not raw HTML (XSS) |
Accessibility (the part many candidates forget): follow the ARIA combobox pattern.
- The input has
role="combobox",aria-expanded,aria-controls(the list's id) andaria-activedescendant(the id of the highlighted option), so focus stays in the input while a screen reader announces the highlighted option. - The list has
role="listbox", and each itemrole="option"witharia-selected. - Keyboard: Down and Up arrows move the highlight, Enter selects, Escape closes, Tab leaves.
- Announce "5 results available" in an
aria-liveregion.
The core logic as a small hook:
import { useEffect, useRef, useState } from "react";
type Suggestion = { id: string; label: string };
export function useSuggestions(query: string, fetcher: (q: string, signal: AbortSignal) => Promise<Suggestion[]>, minChars = 2, delayMs = 300) {
const [results, setResults] = useState<Suggestion[]>([]);
const [status, setStatus] = useState<"idle" | "loading" | "error" | "success">("idle");
const cache = useRef(new Map<string, Suggestion[]>());
useEffect(() => {
const q = query.trim().toLowerCase();
if (q.length < minChars) {
setResults([]);
setStatus("idle");
return;
}
const cached = cache.current.get(q);
if (cached) {
setResults(cached);
setStatus("success");
return;
}
const controller = new AbortController();
const timer = setTimeout(() => {
setStatus("loading");
fetcher(q, controller.signal)
.then((data) => {
cache.current.set(q, data);
setResults(data);
setStatus("success");
})
.catch(() => {
if (!controller.signal.aborted) setStatus("error");
});
}, delayMs);
return () => {
clearTimeout(timer);
controller.abort();
};
}, [query, fetcher, minChars, delayMs]);
return { results, status };
}The clean-up cancels both the pending debounce timer and any in-flight request whenever the query changes. Note that fetcher must be stable (defined outside the component or wrapped in useCallback, Lesson 168), otherwise the effect would re-run on every render.
Design 2: Infinite scroll feed
The question: "Design a feed that loads more posts as the user scrolls", like a social media timeline.
Requirements: item types (text, images, video); real-time new posts; how many items a user might scroll through (hundreds or thousands); restoring the position when coming back.
API: cursor-based pagination: GET /api/feed?cursor=xyz&limit=20 returns { items, nextCursor }. The cursor points to the last item seen, so new posts at the top do not cause duplicates or skipped items, which happens with ?page=2 offsets.
Detecting the bottom: use an IntersectionObserver (Lesson 90) on a small "sentinel" element after the last item. When it becomes visible (with a rootMargin such as 600 px, so loading starts before the user reaches the end), load the next page. This is far more efficient than listening to every scroll event.
import { useEffect, useRef } from "react";
export function useLoadMore(onLoadMore: () => void, enabled: boolean) {
const sentinelRef = useRef<HTMLDivElement>(null);
useEffect(() => {
const node = sentinelRef.current;
if (!node || !enabled) return;
const observer = new IntersectionObserver(
(entries) => {
if (entries.some((e) => e.isIntersecting)) onLoadMore();
},
{ rootMargin: "600px" }
);
observer.observe(node);
return () => observer.disconnect();
}, [onLoadMore, enabled]);
return sentinelRef;
}Set enabled to false while a page is loading or when nextCursor is null, to avoid duplicate requests.
Important details:
| Concern | Approach |
|---|---|
| Thousands of DOM nodes | Virtualise the list (render only visible items, Lesson 172), with care for items of different heights |
| Layout shift from images | Reserve space with width and height or aspect-ratio |
| New posts arriving | Do not insert them at the top while the user reads; show a "5 new posts" button |
| Going back to the feed | Restore the scroll position and cached pages (TanStack Query's infinite queries help) |
| Errors | Show a "Retry" button at the end of the list instead of failing silently |
| Accessibility | Infinite scroll can trap keyboard users and hide the footer. Offer a "Load more" button as an alternative, use role="feed" with aria-busy while loading, and move focus sensibly |
| SEO | Search engines may not scroll; provide paginated URLs if the content must be indexed |
Trade-off: infinite scroll suits browsing (social feeds, images). Classic pagination suits finding and returning to things (search results, admin tables, shops), because users can bookmark page 3.
Design 3: Data table
The question: "Design a table component for an admin panel: thousands of orders, with sorting, filtering, pagination and row selection."
Requirements: how many rows (hundreds or millions); which columns sort and filter; editing inline; selecting rows for bulk actions; exporting to CSV; mobile layout.
Client-side or server-side? The key decision:
| Client-side | Server-side | |
|---|---|---|
| Data size | Up to a few thousand rows | Large or growing data |
| How | Load all rows once; sort, filter and page in the browser | Send sort, filter, page or cursor to the API; database does the work |
| Pros | Instant interactions, simple API | Scales, less memory, always fresh |
| Cons | Slow first load, memory use | A request per interaction (debounce filters, show loading) |
API (server-side): GET /api/orders?status=paid&q=smith&sort=-createdAt&page=3&pageSize=50 returns { rows, total }. (Database indexes for these sorts and filters are covered in Lesson 220.)
State in the URL: keep sort, filters and page in the query string, so users can bookmark, share and refresh without losing their view, and the browser Back button works.
Component API: a column definition array (config-driven UI, Lesson 175):
import type { ReactNode } from "react";
export type Column<T> = {
key: string;
header: string;
cell: (row: T) => ReactNode;
sortValue?: (row: T) => string | number;
align?: "left" | "right";
};
export function sortRows<T>(rows: T[], columns: Column<T>[], sortKey: string | null, direction: "asc" | "desc"): T[] {
const column = columns.find((c) => c.key === sortKey);
if (!column?.sortValue) return rows;
const getValue = column.sortValue;
const factor = direction === "asc" ? 1 : -1;
return [...rows].sort((a, b) => {
const va = getValue(a);
const vb = getValue(b);
if (va < vb) return -1 * factor;
if (va > vb) return 1 * factor;
return 0;
});
}Libraries such as TanStack Table provide sorting, filtering, pagination, selection and column resizing as "headless" logic, while you control the markup and styles.
Performance: virtualise rows for very large client-side tables, memoise sorted and filtered results (Lesson 168), debounce filter inputs, and keep row components cheap.
Accessibility:
- Use a real
<table>with<th scope="col">and a<caption>(Lesson 11). - Sortable headers contain a button, and the header cell has
aria-sort="ascending","descending"or"none". - Row checkboxes have labels like "Select order 1042"; the header checkbox selects all.
- Announce result changes ("Showing 50 of 1,240 orders") in a live region.
- On small screens: let the table scroll horizontally inside a labelled region, or switch to a card layout.
Extras worth mentioning: sticky header, column visibility settings saved per user, bulk actions on selected rows, CSV export (server-side for big data), inline editing with optimistic updates.
How to say it in an interview
"For an autocomplete I debounce input with a minimum length, cancel stale requests with AbortController, cache by query, and follow the ARIA combobox pattern with aria-activedescendant and full keyboard support. For infinite scroll I use cursor pagination and an IntersectionObserver sentinel with a root margin, virtualise long lists, reserve image space, offer a load more button for accessibility, and show new posts behind a button. For a data table, the main decision is client-side versus server-side processing based on data size; I keep sort, filter and page in the URL, define columns as config, and use a real table with aria-sort on sortable headers."
Key words
| Word | Meaning |
|---|---|
| Autocomplete / typeahead | Suggestions shown while typing |
| Combobox | An input with a pop-up list of options (ARIA pattern) |
| aria-activedescendant | Points to the highlighted option while focus stays in the input |
| Cursor pagination | Paging with a pointer to the last item instead of page numbers |
| Sentinel | An invisible element whose visibility triggers loading more |
| Headless library | Provides logic and state but no markup or styles |
| aria-sort | Tells assistive technology how a column is sorted |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.