2 comments

[ 4.3 ms ] story [ 20.1 ms ] thread
(comment deleted)
Another solution, apart from custom hooks is the queryOptions helper function:

  function postQuery(id: number) {
    return queryOptions({
      queryKey: ["posts", id],
      queryFn: () => fetchPost(String(id))
    }) 
  }

  function App() {
    const [id, setId] = useState(1);
    const { data, error, isPending } = useQuery(postQuery(id))
  }
See https://tanstack.com/query/latest/docs/framework/react/types...

In addition to fixing this leak, it has several advantages:

- It DRYs the QueryKey

- In Typescript, it tags the QueryKey with the return type, giving you type safety in utility functions such as setQueryData

- Unlike custom hooks, it gives you more flexibility if you want to use useSuspenseQuery, useQueries or if you want to prefetch the query.