Skip to main content

useQuery

The useQuery hook executes an asynchronous operation like fetch in a way that supports Suspense. It's based on react-query. You can use this hook to call any third-party APIs from a server component.

Note: If you're making a simple fetch call on the server, then we recommend using the fetchSync hook instead.

Example code

import {useQuery} from '@shopify/hydrogen';

export default function Page() {
const {data} = useQuery(['unique', 'key'], async () => {
const response = await fetch('https://my.api.com/data.json', {
headers: {
accept: 'application/json',
},
});

return await response.json();
});

return <h1>{data.title}</h1>;
}

Arguments

The useQuery hook takes the following arguments:

KeyRequiredDescription
keyYesA string or an array to uniquely identify the query.
queryFnYesAn asynchronous query function like fetch which returns data.
queryOptionsNoThe options to manage the cache behavior of the sub-request.

The queryOptions object accepts the following properties:

KeyRequiredDescription
cacheNoThe caching strategy to help you determine which cache control header to set.
preloadNoWhether to preload the request. It defaults to true only when the CachingStrategy is not CacheNone. Specify false to disable or use '*' to preload the query for all requests.
shouldCacheResponseNoA function that inspects the response body to determine if it should be cached.

Return value

The useQuery returns an object with the following key:

KeyDescription
dataThe data returned by the query.