Is `useOptimistic` relevant if use use react-query ?
I mean the useMutation hook covers the same thing, right?
4 Replies
extended-salmon•15mo ago
What’s that?
foreign-sapphireOP•15mo ago
useOptimistic – React
The library for web and native user interfaces
extended-salmon•11mo ago
Very good question. I'm following the query.gg lesson and I was wondering the same. I didn't yet reach the optimistic part of the tutorial but once I have finished it, I will try to see how I can and if it make sense to combine anything with the useOptimistic hook. On the same page I was wondering if the new react 19 hook
useActionState
can be used with react query. I will try out and come back with my experiments.
My first try with the new useOptimistic
hook is not very compelling. It force us to lift the useMutate and useQuery at the same level in case the form and the list could be in different components. Also it force to have the logic inside the component because the update and the list must be provided together to the useOptimistic
hook. And at the end, it didn't even work on my side. I did not look deeply why, but it seems that there is always a re-render after the addOptimisticItem
callback is called which restore the initial itemList.
I feel like the new hook is not a good match to use with react query. and to be honest I prefere the react query way because it keep things isolated but still we have a way to control what the cache return. So I will stick with the provided optimistic way react query propose to use.
Now I will try out the new useActionState
hook I'm more confident that I can use it with react query but will see.
hold my beer I have an idea...
I have tried out a pattern where I group together a useQuery
and useMutation
in a common hook in order to handle everything in the same place. The pattern seems good because we have then everything in one hook that belong together (a GET and a POST) that manipulate the same data.
However it doesn't work neither because the issue seems to be the same as previously. As soon a the hook re-render for any reason (basically because one of the hook useQuery
or useMutation
change a state, it will put back the original state in the useOptimistic
hook I think that useOptimistic
hook is a good alternative to react query, but with the fine grained control we have over the cache with react query I definitly think useOptimistic
should not and cannot be coupled with react query. We can use it if we change the cache but then we juste do the same thing twice and it doesn't make any sense.extended-salmon•11mo ago
I put together a small post in the react query discussion : https://github.com/TanStack/query/discussions/8263
GitHub
New
useOptimistic
hook and React Query · TanStack query · Discuss...After following the query.gg course and espcially the Optimistic-Update chapter, I was curious how we could use the new useOptimistic hook from React 19. As I could not find anything, I put my hand...