Client-Side Filtering and Sorting with Async Data
System DesignModel answerLast updated
Design a frontend component that fetches paginated data, applies client-side search and sort, and handles race conditions efficiently.
Problem: Interactive Data Table with Remote Pagination
You're building a user interface that displays a catalog of films. The data arrives from a backend endpoint in pages, and users need to search and reorder the results without leaving the current page.
Your Task
Design and implement (or describe the architecture for) a component that:
-
Loads data from a paginated endpoint — The API is
GET /api/movies?page={n}and returns:{ "data": [ {"id": 1, "title": "Inception", "year": 2010}, {"id": 2, "title": "The Matrix", "year": 1999} ], "totalPages": 12 }Each page contains up to 50 records. Handle loading states and request failures gracefully.
-
Implement a search filter — Users type into a text box to filter the current page by title (case-insensitive substring match). The filter should feel instant but not trigger excessive re-renders or computation.
-
Provide sort controls — Users can toggle between sorting by title (alphabetical) or release year (most recent first). Sorting applies to the filtered subset.
-
Optimize for responsiveness — The interface should remain snappy even when users type quickly or switch pages rapidly.
Constraints
- The component must handle edge cases: empty results, network errors, concurrent requests, and malformed data.
- Assume React or a similar declarative framework.
- Focus on clean separation between server state, UI state, and computed state.
Example Interaction
- User loads page 3 (shows 50 movies).
- User types "dark" in the search box.
- Component filters the 50 loaded movies to ~8 matches containing "dark" in the title.
- User switches sort to "year" — the 8 matches reorder by year, most recent first.
- User navigates to page 4 — the search and sort preferences persist, but the filter now applies to the new page's 50 movies.
What We're Evaluating
- How you structure state to avoid bugs (stale data, race conditions, unnecessary re-renders).
- Your approach to async data fetching and error handling.
- Performance considerations for filtering and sorting.
- Code clarity and separation of concerns.
Hints
Hint 1
Separate server state (the raw fetched data) from derived state (filtered and sorted results). Never store computed values in useState.
Hint 2
Debounce the search input to reduce computation, but let the input itself update immediately so typing feels responsive.
Hint 3
Use an AbortController to cancel in-flight requests when the user changes pages before the previous request completes.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Solution: Layered State Architecture
Core Design Principle
The architecture separates three kinds of state, each with a single source of truth:
- Server state: the raw page of movies, loading status, and any error. This lives in a custom hook and is never modified after fetch.
- UI state: the current page number, the raw search text (updated on every keystroke), and the sort preference.
- Derived state: the visible list of movies, computed by sorting and then filtering. This is never stored in
useState—it's always recalculated viauseMemofrom server and UI state.
This separation ensures:
- Typing in the search box never waits for a debounced callback to update the input field itself.
- Sorting and filtering never drift out of sync because they read from the same canonical source.
- Race conditions are contained to the fetch logic and resolved with abort signals.
Implementation Strategy
1. Data Fetching with Race Condition Handling
The useMovies(page) hook manages all server interaction. Each time page changes, a new AbortController is created. When the effect re-runs (because the user clicked to page 4 before page 3 finished loading), the cleanup function aborts the previous request. This prevents slow responses from overwriting newer data.
useEffect(() => {
const controller = new AbortController();
setState({ ...state, status: 'loading' }); // keep old data visible during load
fetch(`/api/movies?page=${page}`, { signal: controller.signal })
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
})
.then(({ data, totalPages }) => {
setState({ status: 'success', movies: data ?? [], totalPages, error: null });
})
.catch(err => {
if (err.name === 'AbortError') return; // request superseded, ignore
setState({ status: 'error', error: err, movies: state.movies });
});
return () => controller.abort();
}, [page]);
Key points:
- We check
res.okexplicitly becausefetchdoes not reject on 4xx/5xx. AbortErroris silently ignored—it means a newer request is already in flight.- During loading, the previous page's data remains visible (optionally dimmed with CSS or
aria-busy), preventing layout jank.
2. Debounced Search
The search input updates its own query state immediately, so the user sees their keystrokes without delay. A separate useDebouncedValue hook tracks the query with a 300ms delay. Only the debounced value drives the filter computation.
function useDebouncedValue(value, delay = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebounced(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debounced;
}
This keeps the UI responsive while avoiding repeated O(n) filters for every keystroke.
3. Sort Then Filter
Both operations are pure functions that live outside React:
const collator = new Intl.Collator(undefined, { sensitivity: 'base' });
function sortMovies(movies, sortKey) {
const copy = [...movies]; // never mutate server state
if (sortKey === 'year') {
copy.sort((a, b) => (b.year ?? 0) - (a.year ?? 0) || collator.compare(a.title, b.title));
} else {
copy.sort((a, b) => collator.compare(a.title, b.title));
}
return copy;
}
function filterMovies(movies, query) {
const q = query.trim().toLowerCase();
if (!q) return movies;
return movies.filter(m => (m.title ?? '').toLowerCase().includes(q));
}
In the component, two useMemo calls chain these operations:
const sorted = useMemo(() => sortMovies(movies, sortKey), [movies, sortKey]);
const visible = useMemo(() => filterMovies(sorted, debouncedQuery), [sorted, debouncedQuery]);
Order matters: sort first, then filter. Filtering a sorted array preserves order, so the result is equivalent to "filter, then sort the subset", but the O(n log n) sort only reruns when the raw data or sort key changes. Each debounced keystroke costs only O(n).
Why not cache lowercase titles? We could precompute searchKey: title.toLowerCase() when data arrives, saving repeated lowercasing during filtering. This trades memory (50 extra strings per page) for speed (O(1) per comparison instead of O(m)). With 50-item pages, the gain is marginal, but the pattern scales.
4. Edge Cases
- Empty API response:
data ?? []ensures we never iterate overnull. The UI distinguishes "no movies available" (source empty) from "no matches for 'xyz'" (filter empty). - Network failure: The error state includes a Retry button that re-triggers the fetch without changing the page number.
- Whitespace-only query: Trimmed and treated as no filter.
- Missing or malformed fields:
title ?? ''andyear ?? 0prevent one bad record from crashing the sort. - Component unmounts mid-request: Abort prevents setting state on an unmounted component (though React 18+ mostly handles this).
Complexity Analysis
With n = 50 (movies per page), k = matches, and m = average title length:
| Operation | Time | Triggered by |
|---|---|---|
| Sort | O(n log n) | new data or sort key change |
| Filter | O(n·m) | debounced query change |
| Render | O(k) | any derived state change |
Space: O(n) for the sorted copy. With 50 items this is negligible. The architecture still works at 500 or 5,000 items because the expensive step (sort) is isolated from the frequent one (filter).
Why This Works
- No stale closures: All state is in hooks with proper dependency arrays.
- No redundant computation:
useMemoensures sorting and filtering only re-run when their inputs change. - No race conditions: Abort signals cancel superseded requests.
- Testability: Pure functions (
sortMovies,filterMovies) can be unit-tested in isolation. - Accessibility: The component should include
aria-liveregions for status updates andaria-busyduring loading.
Alternative: Server-Side Search
If the dataset grows beyond a few hundred items per page, or if search needs to span all pages, move filtering to the backend:
GET /api/movies?page={n}&q={query}&sort={key}
The debounced query becomes part of the fetch key. The abort pattern still handles races. The tradeoff: network latency replaces local computation, so you may need to show a loading spinner during search rather than instant feedback.
Common Mistakes
- Storing filtered results in
useState: This creates two sources of truth. When the raw data or sort key changes, the filtered state must be manually synchronized or it drifts out of sync. - Debouncing the input value itself: This makes typing feel sluggish. Debounce only the derived computation, not the input.
- Not aborting requests: Without abort signals, a slow page 2 request can overwrite page 3 after the user navigates forward.
- Mutating the original array:
array.sort()modifies in place. Always copy first. - Using
===for string comparison: Case-insensitive, locale-aware comparison requirestoLowerCase()orIntl.Collator.
This architecture generalizes to any "fetch, filter, sort" UI: product catalogs, user directories, log viewers, etc. The key is treating server state as immutable and deriving everything else from it.