My Take on “Thinking in React Query”

Bipin Maharjan

--

React Query is a state manager like Redux or Zustand, but it only manages async data. Since it’s a state manager like others, it can also subscribe to data changes, but the data comes from an async source. We subscribe to React Query data changes using the queryKey property.

React Query Hooks with “queryKey”

We can call the React Query Hooks with the same queryKey wherever we need to access the data and subscribe to the data changes.

What this approach does is make React Query a single source of truth, and when the truth changes, it will update all the components that are subscribed to the data changes.

useIssues() hook uses React Query. Using React Query wherever you want.

If we use React Query wherever we want, won’t it spam the backend server with the same request?

No, when React Query data is fetched, it will cache the data and only revalidate the data when it becomes stale.

So when is data considered stale?

Data is considered stale after a certain stale time. By default, React Query has 0ms as a stale time, but you can configure it in the queryClient options or on the individual query level. You can also use the Infinity value to never consider the data as stale.

// Configuring stale time in queryClient
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60 * 5, // 5 minutes
},
},
});
// Configuring stale time in individual query
const { data } = useQuery("todos", fetchTodos, {
staleTime: 1000 * 60 * 5, // 5 minutes
});

Since React Query is also used to sync the data, it is also considered a Data synchronization tool.

So, How does it re-sync the data?

When the data is fresh (opposite of stale), it will return from the cache. When the data is stale, it will still return the data from the cache, but it will also trigger the revalidation, which will fetch the data and replace the stale data with the fresh data.

React Query synchronization is not only triggered by data being stale, but also due to the queryKey changes like searching with a keyword or fetching data with pagination. In these scenarios, we use a filter key (search keyword/page number) in the queryKey to trigger the revalidation.

// Using filter key in queryKey
const { data } = useQuery(["todos", { page: 1 }], fetchTodos);

To exchange the filter key state within different components of the app, we can simply use the traditional state managers to share client-side state.

Resource:

--

--

No responses yet

Write a response