Skip to content

Instantly share code, notes, and snippets.

@lourd
Last active April 1, 2026 02:55
Show Gist options
  • Select an option

  • Save lourd/eae2266d619a5f1a7f6eb47e7dc735b7 to your computer and use it in GitHub Desktop.

Select an option

Save lourd/eae2266d619a5f1a7f6eb47e7dc735b7 to your computer and use it in GitHub Desktop.
Hook for returning a cached promise from a TanStack React Query to `use` in child component
import {
FetchQueryOptions,
Query,
QueryClient,
QueryKey,
} from "@tanstack/react-query";
/**
* Returns a function hooked up to the React Query cache that calls `queryClient.fetchQuery` or
* returns the existing, cached promise.
*/
export function useFetchQuery(queryClient: QueryClient) {
return function fetchQueryWithCachedPromise<
TQueryFnData,
TError,
TData,
TQueryKey extends QueryKey,
>(
options: FetchQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
): Promise<TData> {
const query = queryClient
.getQueryCache()
.find<TQueryFnData, TError, TData>(options) as
| Query<TQueryFnData, TError, TData, TQueryKey>
| undefined;
if (!query?.promise) {
return queryClient.fetchQuery(options);
}
if (query.state.status === "pending") {
return query.promise;
}
const time =
typeof options.staleTime === "function"
? options.staleTime(query)
: options.staleTime;
const isStale = query.isStaleByTime(time);
if (isStale) {
return queryClient.fetchQuery(options);
}
return query.promise;
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment