This blog post is the second in a series:
- Things I learned while using React Query - Part 1 (this post)
- Things I learned while using React Query - Part 2
I’ve been using React Query in real world applications for over 8 months now, and I want to share with you some of the things I found useful to know when using it. This is the first part of a blog series.
React Query is a caching layer that improves the developer experience and the user experience. The cache lives in memory, within your application, which means there is NO server or browser caching involved.
One of the most common mistakes when starting with React Query is to treat it like a traditional cache. Many developers are taken by surprise when they see the background refetch of the data. They expect to have only the initial network request and then to have the data served (only) from the cache.
But this is not the case.
React Query uses the stale-while-revalidate caching strategy in the attempt of keeping the user as up to date as possible with the server data without affecting the user experience.
In the documentation or in any other resource on React Query you will see many references to the different states in which a query can be.
inactive. Understanding why a
query is in a certain state and when it will transition to a new state is
crucial if you want to be proficient with React Query.
They are the backbone of the library.
As you can see in the above diagram, the
cacheTime play a
crucial role in deciding the state of the query. Make sure you understand when
to use staleTime and when to use cacheTime. I like how
@TkDodo describes the differences between the two.
staleTime = the duration until a query transitions from fresh to stale.
cacheTime = the duration until inactive queries will be removed from the cache.
React Query ships with built-in dev tools. They can be extremely useful when learning the library.
Having a graphical representation of the different states in which a certain query is in will make it easier to understand them
Be aware of the important defaults and throughly understand them to make learning and debugging easier.