How should I use Tanstack query for expensive calculation?

I have an expensive calculation that requires a bunch of parameters to be set beforehand and I would like to run it after a user clicks a button and it will return a big object which I will show in a React component.
function Todos() {
const { isLoading, isError, data, error, refetch, isFetching } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodoList,
enabled: false,
})
function Todos() {
const { isLoading, isError, data, error, refetch, isFetching } = useQuery({
queryKey: ['todos'],
queryFn: fetchTodoList,
enabled: false,
})
I can disable to query with enabled: false as shown in the tanstack query docs and refetch whenever the user clicks the button. But it clearly states this is not the idiomatic way of using tanstack query in the docs. Is there a pattern that I am missing that would allow me to handle expensive queries in a different manner or do I have to use the non-idiomatic way of doing things for this use case?
Solution:
From the documentation:
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook....
Jump to solution
4 Replies
msvc
msvc3w ago
mutations are able to return data as well. If you're looking to have an action be triggered, use that instead of a query.
Solution
msvc
msvc3w ago
From the documentation:
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook.
msvc
msvc3w ago
Mutations | TanStack Query React Docs
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook. Here's an example of a mutation t...
AlpMimaroglu
AlpMimarogluOP3w ago
Thank you so much. I was aware of mutations but didn't know they could be used for returning back data. So the idiomatic way is to use a mutation for this situation.

Did you find this page helpful?