In my application, I have a paginated feed containing posts retrieved from the /feed endpoint.
Each feed post has...
postIdpostTitlepostBodypostCreator(object)
Each postCreator object has...
userIduserNameuserBiouserImageUrl
As suggested by Redux, I'm currently...
- Extracting the
postCreatorobjects and storing them in their own globalusersStore(using Zustand) - Replacing the
postCreatorobjects with the relevantpostCreatorId(which references a user in the globalusersStore) in each post - Storing the posts in their own
postsStore(using Zustand)
The benefits of this are...
- If a user updates their information (e.g. name or bio), we only have to update their record in the usersStore, and their information will be updated across the whole app (their post creator info in the feed posts UI, their profile image in the tab-bar etc)
- We don't have to re-request the data from the /feed endpoint to get the posts containing the updated
postCreatorobject. 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
usersStoreandpostStoreto update the user's information in a single place, as described above.Scrap the global
usersStore, and update thepostCreatorinformation directly in React-Query's cache for the/feedinfiniteQuery, usingqueryClient.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?