Controlling how UI updates with refetched data
Hello!
The default experience when using react-query is that stale data is shown while the given resource is refetched, then if the resolved data is different, it automatically gets updated in the UI, typically just sorta "popping" in, if you understand what I mean.
This is due to how we tend to directly use the
data returned from useQuery, something like (warning: pseudocode ahead):
So as expected, a rerender with different data will cause that data to just "appear" in the UI.
However, there are use cases where this experience is less than ideal. What if I don't want the data to just pop in? Depending on the data, it can be disruptive and disorienting. What if I want to "control" when the new data appears?
For example, I could prefer the following flow:
1. Component mounts, cached / stale data is shown
2. Data refetched in bg
3. Resolved data comes back, it's different than the stale data
4. We indicate to the user (e.g. via a toast) that the data has changed, providing them with a button to click if they want to refresh the view
5. Upon clicking the button, THEN the new data is added to the UI.
So I started working on this by using multiple pieces of state, refs, effects, & so on.. but before I went further down that.. dark path.. I wanted to reach out first and see if there's a community solution / idiomatic way of handling this already? Or am I actually just missing something and this is more straightforward than I'm currently thinking about it?
Hope that makes sense and thanks for the time!2 Replies
rare-sapphire•4y ago
Best way would indeed be to copy data with an effect to local state, then, if the effect runs again (=data from RQ has changed), you display the message and potentially set state again. In your ui, you only show the local state copy.
environmental-roseOP•4y ago
Great, thanks!