DEV Community

Marin Virdol
Marin Virdol

Posted on • Originally published at codemachine.dev

Things I learned while using React Query - Part 1

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 light caching layer

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.

Understand the different states of a query and the differences between them

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.

These are: fresh, fetching, stale and 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 this library.

React Query States Diagram

As you can see in the above diagram, the staleTime and 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

Use the built-in dev tools to visualize the states of your queries

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

React Query Dev Tools

Know the important defaults

Be aware of the important defaults and throughly understand them to make learning and debugging easier.

Top comments (0)