---
title: useQuery
---

`useQuery` is a data fetching hook that uses [Suspense](https://reactjs.org/docs/react-api.html#reactsuspense) and has an API inspired by [react-query](https://react-query.tanstack.com). It can be used when you want to fetch some data from your own endpoints or from a third-party API that allows [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). CORS is necessary because `useQuery` may run on the client.

Let's see an example that uses the free [Pokéapi](https://pokeapi.co/):

<CodeViewer
  name="guide-samples"
  openFiles={["src/routes/use-query/[pokemon].page.tsx"]}
  url="/use-query/pikachu"
/>

`useQuery` takes a query key that uniquely identifies the fetched data and a query function that does the actual fetching. The function must be isomorphic, which means it must be able to run on the server as well as on the client. That means you can't use server-only APIs (database, filesystem etc.) or client-only APIs (`window`, `document`, `localStorage` etc.).

The fetcher function takes a `PageContext` object. This object contains a `fetch` method which has the same API as [`window.fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API). On the client, it is in fact `window.fetch`. On the server, it tries to emulate `window.fetch` as closely as possible. It considers the referer as its base URL and, if allowed by the `credentials` option, **forwards the credentials** (`Cookie` and `Authorization` headers). Also, **requests to your own API routes are optimized** so that they don't go through the network roundtrip. A global `fetch` function is also available on the server but it doesn't forward credentials, optimize requests, or support relative URLs in most deployment targets.

If you've used similar data fetching hooks before, you may have noticed that this sample component doesn't do anything to handle the loading state or errors. Those are handled higher up in the component tree with Suspense fallbacks and error boundaries respectively. This way, your component code stays clean and focused.
