Skip to content

Export QueryOptions instead of hooks #14

@kyleamazza

Description

@kyleamazza

Context

Per recommendation from a react-query maintainer and from a similar change in tRPC it is recommended to export only QueryOptions instead of a hook itself. The main reason backing this is that QueryOptions are more stable than the QueryClient, since QueryClient relies more heavily on the exact version of react-query (particularly with the types).

Additionally, giving access to the queryOptions simplifies the access of the queryKey, making it easier to handle query invalidation.

(See similar discussion in trpc's issues)

Change

  • Modify the generated code to export QueryOptions instead of a query hook.

Example

Current:

import { usePets } from '~/api/__generated__/petStore';

const MyComponent = ({ petStoreId: string }) => {
  const petsQuery = usePets(petStoreId);

  const petMutation = useCreatePet({
    onSettled: () => {
      queryClient.invalidateQueries({
        queryKey: // ??
      });
    }
  });
}

Proposed:

import { useQuery, useQueryClient } from '@tanstack/react-query';
import { getPetsQueryOptions, createPetMutationOptions } from '~/api/__generated/petStore';

const MyComponent = ({ petStoreId: string }) => {
  const queryClient = useQueryClient();
  const getPets = getPetsQueryOptions(petStoreId);
  const petsQuery = useQuery(getPets);

  const petMutation = useMutation(createPetMutationOptions({
    onSettled: () => {
      queryClient.invalidateQueries({
        queryKey: getPets.queryKey
      });
    }
  });
}

Consequences

  • Consumers will need to update all usages of the current style of hook to using the new export QueryOptions within react-query's base useQuery.
  • Suspense queries should be able to use the same QueryOptions, so the equivalent currently-export suspense hooks can be dropped.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions