React components that fetch data often need to show loading indicators, display results, and handle errors. Managing requests directly in each component with useEffect and useState means repeating request setup, state management, and cleanup. This repetition makes it easy to forget to reset state or allow an outdated response to overwrite newer data.
Data fetching libraries such as SWR, TanStack Query, and fate handle request lifecycles so components can focus on displaying data.
A useQuery hook makes this logic reusable, so components can focus on what to fetch and how to render the result. Implement the hook to run a function returning a promise, expose loading, success, or error state, and ignore outdated results. Each hook instance manages its own requests.
export default function Component({ param }) {const request = useQuery(async () => {const response = await getDataFromServer(param);return response.data;}, [param]);if (request.status === 'loading') {return <p>Loading...</p>;}if (request.status === 'error') {const message =request.error instanceof Error? request.error.message: String(request.error);return <p>Error: {message}</p>;}return <p>Data: {request.data}</p>;}
fn: () => Promise: A function that returns a promisedeps: DependencyList: An array of dependencies, similar to the second argument of useEffect. Unlike useEffect, this defaults to []The hook returns an object that has different properties depending on the state of the promise.
status: 'loading': The promise is still pendingstatus: 'error': The promise was rejectederror: unknown: The value that caused the promise to be rejectedstatus: 'success': The promise was resolveddata: The data returned when the promise from fn resolves{ status: 'loading' } when it starts a new request.deps should start a new request and ignore stale results from earlier requests.