Frontend System Design · Lesson 78 of 86 · 4 min
Integrating Backend Search Services
This isn't just about fetching data. It's about designing the contract, managing complex state, and articulating the trade-offs of a real-time UI feature.
When you're asked to design a typeahead search, the interviewer is testing your ability to think through the entire frontend system. They want to see how you handle user input, network requests, state management, and potential race conditions. A shallow answer that just mentions fetch and useState is a red flag.
Define the API Contract First
Before writing a line of client code, define the API. This forces clarity on what the frontend controls and what the backend provides. A well-defined contract is the foundation of a decoupled, maintainable system.
Your query parameters are the frontend's control panel. A robust search endpoint needs more than just a query string. You will need:
q: The user's search term.pageoroffset: For pagination.pageSizeorlimit: To control the number of results per page.sortBy&sortOrder: For user-controlled sorting.filters: A structured way to send faceted search criteria, often as a stringified JSON object or repeated query parameters (category=electronics&category=clothing).
The response payload should give the UI everything it needs to render the current view and the controls for other views. Don't make the client calculate metadata.
results: An array of search result items.totalCount: The total number of matching documents, essential for calculating pagination.totalPages:Math.ceil(totalCount / pageSize), calculated on the server.
In an interview, start here. When asked to design a search UI, begin by saying, "First, let's define the API contract." Sketch out the request and response shapes. This immediately shows you're thinking about system boundaries, not just a single component. It also lets you control the assumptions for the rest of the problem.
Manage All Search Parameters as a Single State Object
Avoid scattering search state across multiple useState hooks. A single state object, representing all possible API parameters, is easier to manage, update, and synchronize.
const [searchParams, setSearchParams] = useState({
q: '',
page: 1,
sortBy: 'relevance',
filters: {
category: 'electronics'
}
});
When a user types, changes a filter, or clicks a pagination button, you update this single object. This triggers a useEffect hook that re-runs the search. This pattern centralizes the logic for fetching data.
The trap: Forgetting the URL. If your search state lives only in component memory, the URL doesn't change. This breaks sharing, bookmarking, and the browser's back button. The URL is a form of state. Use the URLSearchParams API and your router's history management to keep the component state and the URL in sync. A change in the URL should update your state object, and an update to your state object should be reflected in the URL.
Orchestrate the Request-Response Flow
The core of the frontend logic is a useEffect hook that observes the searchParams object. This effect is responsible for the entire lifecycle of a single search request.
Here's the sequence:
- A user action (typing, clicking a filter) updates the
searchParamsstate. - The
useEffecthook is triggered by this state change. - Inside the effect, you start a debounced timer. If the effect re-runs before the timer fires, the old timer is cleared.
- When the timer fires, set a
loadingstate to true. - Make the API call, passing the
searchParams. - On success, update the
resultsstate and setloadingto false. - On failure, update an
errorstate and setloadingto false.
This flow is the minimum viable implementation for a good user experience. It provides visual feedback for loading and error states and protects your backend from being overwhelmed.
Prevent Race Conditions with AbortController
The trap: A fast user types "A", then "B". The request for "B" might return before the request for "A". If you just update state as responses arrive, the UI will show results for "B", then flicker and incorrectly show results for "A". This is a classic race condition.
The solution is to cancel the previous request whenever a new one is initiated. The AbortController API is designed for this. Create a new controller for each request inside your useEffect, and call its abort() method in the effect's cleanup function.
This demonstrates a deep understanding of asynchronous browser behavior and is a huge plus in an interview.
useEffect(() => {
// Create a controller for this specific request
const controller = new AbortController();
const fetchData = async () => {
if (!searchParams.q) return;
try {
// Pass the signal to your fetch call
const data = await api.search(searchParams, { signal: controller.signal });
setResults(data);
} catch (error) {
// Aborted requests throw an error; ignore it.
if (error.name === 'AbortError') {
console.log('Fetch aborted');
} else {
setError(error);
}
}
};
// Debounce the actual fetch
const timerId = setTimeout(fetchData, 300);
// The cleanup function runs when the effect re-triggers or the component unmounts
return () => {
clearTimeout(timerId);
controller.abort(); // Abort the in-flight request
};
}, [searchParams]); // Re-run effect when params change
This small block of code is more valuable to discuss than a hundred lines of UI boilerplate. It correctly handles debouncing, cancellation, and error states.
Try it
Take an existing project with a simple search input. Refactor it to manage all search parameters (query, page, filters) in a single state object. Then, use the URLSearchParams API to ensure that every change to this state object is reflected in the page URL, and vice-versa.
Next: We'll look at frontend-specific rendering challenges in the next lesson, "Choosing a Chart Library: D3, Chart.js, Recharts".
Lock it in — apply this lesson under interview conditions.