In my application, I have a paginated feed containing posts retrieved from the /feed endpoint.
Each feed post
has...
postId
postTitle
postBody
postCreator
(object)Each postCreator
object has...
userId
userName
userBio
userImageUrl
As suggested by Redux, I'm currently...
postCreator
objects and storing them in their own global usersStore
(using Zustand)postCreator
objects with the relevant postCreatorId
(which references a user in the global usersStore
) in each postpostsStore
(using Zustand)The benefits of this are...
postCreator
object. Especially considering that a user may have scrolled way down the feed at that point in time, so we may have to get hundreds of posts from the /feed endpoint, putting strain on our backend.React-Query/SWR
I have recently discovered React Query and SWR and have heard a lot about how they "remove much of the need for global state", but I'm slightly confused by how they handle the above scenario. After doing some research on React-Query, I'm under the impression that there a few ways to handle this...
Still use the global usersStore
and postStore
to update the user's information in a single place, as described above.
Scrap the global usersStore
, and update the postCreator
information directly in React-Query's cache for the /feed
infiniteQuery, using queryClient.setQueryData
. But we would have to also update the other query caches where the user's information is returned, and what if the cache has expired?
Scrap the global usersStore
, and refetch all of the posts from the /feed endpoint when a user updates their info. However, if a user has scrolled way down the feed at that point in time, we may have to get hundreds of posts from the /feed endpoint, putting strain on our backend. React-Query infinite query refetch docs
What is the best practice way to handle this using React-Query/SWR?
react-query doesn't have a normalized cache. That being said, mostly, there is no need to do any normalization - just keep what the api sends you as your state, retrieve it via useQuery
, and get rid of all redux / zustand global stores that would otherwise hold your server state.
In your example, I see two queries:
useQuery(['user', id])
for the user datauseInfiniteQuery(['feed'])
for the feed of postsWhen rendering your feed
, you'll likely render a Post
component for each entry, which can in turn call the useQuery
that retrieves the user data. If you are worried about the n+1 queries that are being made, and you are in fact already delivering the user-data with the feed, you can manually prime the user-cache in the onSuccess
callback of the feed
query - just take the user data and copy it to the user-cache.
That way, the user-cache becomes the single source of truth for user data, which also updates from the feed query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With