useQuery

useQuery is a data fetching hook that uses Suspense and has an API inspired by react-query. It can be used when you want to fetch some data from your own endpoints or from a third-party API that allows CORS. CORS is necessary because useQuery may run on the client.

Let's see an example that uses the free Pokéapi:

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. 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.