Custom Query Hook
Problem statement
A Custom Query Hook is a senior-level React question that asks you to build a simplified version of React Query or SWR from scratch. The challenge demonstrates your mastery of custom hooks, closure behaviour inside async effects, module-level caching, and the subtle difference between ref and state for preventing race conditions.
Your task is to implement a useQuery(queryKey, fetchFn) hook that fetches data when a component mounts (or when the queryKey changes), caches the result by key so subsequent mounts with the same key return immediately without a network request, exposes isLoading, error, data, and a refetch function, and correctly handles component unmounting mid-fetch to avoid the "update on unmounted component" warning.
This question is deliberately designed to expose whether you understand why React Query exists — and whether you can replicate its core mechanics from first principles.
Requirements & constraints
- useQuery(queryKey, fetchFn) hook that fetches on mount
- Module-level cache: if queryKey has been fetched before, return cached data instantly without fetching
- Returns { data, isLoading, error, refetch } to the caller
- refetch() busts the cache for this key and re-fetches
- Handles component unmounting mid-fetch (no state update on dead component)
- isLoading starts true on first mount, false after fetch completes
- Works correctly when the same queryKey is used by multiple components simultaneously
How to approach Custom Query Hook
The strategy an interviewer expects you to reach for.
Problem Understanding Open by explaining the problem React Query solves — this context impresses interviewers immediately: "Every time a component mounts and calls fetch(), it makes a network request even if we already have that data from 2 seconds ago. React Query (and our useQuery hook) solves this with a cache: if we've already fetched data for this key, return it instantly without a network round-trip. This is called stale-while-revalidate."
The full solution is part of HelloFrontend Pro
The question above is free to read in full. Upgrade to unlock the interactive workspace and the senior-level walkthrough that go with it.
- Live React sandbox pre-wired for this component
- Time-boxed checkpoints that mirror a real 45-minute round
- Interviewer scoring criteria and a full reference implementation
Already a member? Log in to open the workspace.