Build a Data-Fetching React Hook and Wire Up a Dashboard UI
Data Structure DesignModel answerLast updated
Write a React hook that fetches and reshapes API data with loading, error and refetch support, then connect a modal, a collapsible list and action buttons to component state.
You are working in a small React project that already has a stubbed API module and a basic page. Your job has two parts.
Part 1: a data hook
Write a custom hook for function components that:
- Calls the provided API function inside
useEffect, using an async function. - Converts each record from the API's shape into the shape the UI needs. For example, snake_case fields become camelCase, first and last name are merged into one display name, and a timestamp string becomes a
Date. - Returns the transformed data together with
loadinganderrorstate. - Exposes a way to refetch on demand.
Part 2: UI wiring
Change the existing page so that:
- A modal can be opened and closed.
- A list can be expanded to show every item and collapsed back to a short preview.
- Several buttons each perform one simple, clearly defined action, such as refresh, toggle sort order, or open the details of an item.
Every interaction must be driven by component state and by the hook's output.
Because the starter code is not shown here, state the API and shape assumptions you make before you code. Explain how you handle slow responses, failures, empty data and unmounting.
Hints
Hint 1
The function passed to `useEffect` cannot be `async` because it must return either nothing or a cleanup function. Declare an async function inside the effect and call it.
Hint 2
Each effect run should own an `AbortController` and an `active` flag, both disabled in the cleanup. That way an outdated response can never overwrite newer state or update an unmounted component.
Hint 3
Implement refetch by bumping a counter that sits in the effect's dependency array, so refetching uses the same code path as the first load. In the UI, store as little state as you can (booleans, the selected item) and derive the visible list with `useMemo`.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The exercise checks two skills: putting asynchronous work in a reusable hook without race conditions, and keeping UI state minimal so that every control maps to one piece of state.
I would begin by stating assumptions aloud. Suppose the API function is fetchMembers({ signal }) and returns records like { id, first_name, last_name, email, created_at }. The UI wants { id, displayName, email, joinedAt: Date | null }. The pattern is identical for any other shapes.
Hook design
- Async inside the effect.
useEffectmust returnundefinedor a cleanup function, so the callback cannot beasync. Defineloadinside it and call it. - State. Keep
data,loadinganderror, plus a numericreloadKeyused only to trigger refetches. - Stale-response protection. Every effect run creates its own
AbortControllerandactiveflag. The cleanup setsactive = falseand aborts. A slow earlier request therefore cannot overwrite the result of a later one, and nothing is set after unmount. - Pure transform. Put the mapping in a standalone function so it can be unit tested without React.
- Refetch.
refetchincrementsreloadKey, which is in the dependency array. The refetch goes through the same status reset, cleanup and error handling as the initial load, so there is no second code path to keep in sync.
UI design
- Use one boolean for the list being expanded, one for sort direction, and one
selecteditem (nullmeans the modal is closed). - Derive the sorted and visible lists with
useMemo. Never copy server data into extra state, and never mutate the hook's array when sorting. - The modal closes through the close button, a backdrop click, or the Escape key. Register the key listener only while the modal is open and remove it in cleanup.
Code
// useMembers.ts
import { useCallback, useEffect, useState } from "react";
import { fetchMembers, RawMember } from "./api"; // provided
export type Member = {
id: number;
displayName: string;
email: string;
joinedAt: Date | null;
};
export function normalizeMember(raw: RawMember): Member {
const name = [raw.first_name, raw.last_name].filter(Boolean).join(" ").trim();
const date = new Date(raw.created_at);
return {
id: raw.id,
displayName: name || raw.email,
email: raw.email,
joinedAt: Number.isNaN(date.getTime()) ? null : date,
};
}
export function useMembers() {
const [data, setData] = useState<Member[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<Error | null>(null);
const [reloadKey, setReloadKey] = useState(0);
useEffect(() => {
const controller = new AbortController();
let active = true;
const load = async () => {
setLoading(true);
setError(null);
try {
const raw = await fetchMembers({ signal: controller.signal });
if (active) setData((raw ?? []).map(normalizeMember));
} catch (e) {
if (active) setError(e instanceof Error ? e : new Error(String(e)));
} finally {
if (active) setLoading(false);
}
};
load();
return () => {
active = false;
controller.abort();
};
}, [reloadKey]);
const refetch = useCallback(() => setReloadKey((k) => k + 1), []);
return { data, loading, error, refetch };
}
// MemberPanel.tsx
import { useCallback, useEffect, useMemo, useState, ReactNode } from "react";
import { useMembers, Member } from "./useMembers";
const PREVIEW_COUNT = 3;
function Modal(props: { open: boolean; onClose: () => void; children: ReactNode }) {
const { open, onClose, children } = props;
useEffect(() => {
if (!open) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") onClose();
};
window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [open, onClose]);
if (!open) return null;
return (
<div className="backdrop" onClick={onClose}>
<div className="dialog" role="dialog" aria-modal="true"
onClick={(e) => e.stopPropagation()}>
{children}
<button onClick={onClose}>Close</button>
</div>
</div>
);
}
export default function MemberPanel() {
const { data: members, loading, error, refetch } = useMembers();
const [expanded, setExpanded] = useState(false);
const [ascending, setAscending] = useState(true);
const [selected, setSelected] = useState<Member | null>(null);
const closeModal = useCallback(() => setSelected(null), []);
const sorted = useMemo(() => {
const copy = [...members]; // do not mutate hook data
copy.sort((a, b) =>
a.displayName.localeCompare(b.displayName) * (ascending ? 1 : -1));
return copy;
}, [members, ascending]);
const visible = expanded ? sorted : sorted.slice(0, PREVIEW_COUNT);
const canExpand = sorted.length > PREVIEW_COUNT;
if (loading && members.length === 0) return <p>Loading...</p>;
return (
<div>
<div className="toolbar">
<button onClick={refetch} disabled={loading}>
{loading ? "Refreshing..." : "Refresh"}
</button>
<button onClick={() => setAscending((a) => !a)}>
Sort {ascending ? "Z-A" : "A-Z"}
</button>
<button onClick={() => setSelected(sorted[0] ?? null)} disabled={!sorted.length}>
Open first member
</button>
</div>
{error && (
<p role="alert">
Error: {error.message} <button onClick={refetch}>Retry</button>
</p>
)}
{members.length === 0 && !error ? (
<p>No members</p>
) : (
<ul>
{visible.map((m) => (
<li key={m.id}>
{m.displayName}{" "}
<button onClick={() => setSelected(m)}>Details</button>
</li>
))}
</ul>
)}
{canExpand && (
<button onClick={() => setExpanded((x) => !x)}>
{expanded ? "Show less" : `Show all (${sorted.length})`}
</button>
)}
<Modal open={selected !== null} onClose={closeModal}>
{selected && (
<>
<h2>{selected.displayName}</h2>
<p>{selected.email}</p>
<p>Joined: {selected.joinedAt ? selected.joinedAt.toLocaleDateString() : "unknown"}</p>
</>
)}
</Modal>
</div>
);
}
Why it works
- Every fetch, including a refetch, sets
loadingtotrueand clearserrorfirst, andfinallyalways ends loading for the current run. - Only the latest effect run can write state, because older runs are aborted and flagged inactive in cleanup.
- Each button changes one piece of state, and the rendered output is a function of that state, so the UI cannot drift out of sync.
Complexity
- Transform: O(n) time and space.
- Sorting: O(n log n), memoized so it reruns only when the data or direction changes, not when the modal opens.
- Preview slice: O(k) for k preview items.
Edge cases and trade-offs
- Empty response: show a "No members" message and hide the expand button.
- Fewer items than the preview size: no expand button.
- Bad records: a missing name falls back to the email, and an invalid date becomes
null. - Non-
Errorthrows: wrap them soerror.messagealways exists. - Rapid refresh clicks: earlier requests are aborted, so the last click wins.
- Refetch while the modal is open: the modal shows a snapshot. Mention that you could store only the selected id and look the record up in
datato keep it fresh. - Library alternative: in production, a data library such as TanStack Query provides caching and deduplication, but the interview wants you to show the underlying mechanics.
Common mistakes
- Passing an
asyncfunction directly touseEffect. - Omitting cleanup, which allows race conditions and updates after unmount.
- Calling
.sort()on state or props directly, which mutates them. - Storing derived data, such as the visible list, in separate state.
- Forgetting to reset
errorandloadingon a refetch.