In my post about React-Query for managing server state, I talked about the basic concepts for you to start working with React-query. In this post, I would like to talk more about useQuery
hook. More specifically about polling, background data fetching, and data transformation.
Table of Contents
What is polling in React Query?
Polling is the process of repeatedly fetching data, automatically, from a remote data source at regular intervals. By default, useQuery does not fetch data automatically. It needs some sort of trigger.
Suppose you are developing a real-time system where data is frequently changing, and you need to incorporate React Query in the front end. It’s evident that data needs to be fetched regularly from the backend to keep the front end in sync. To achieve this, polling is a viable solution. But, how are you going to implement it? This is where the refetchInterval property of the useQuery hook comes into play. By setting this property to a specified time interval in milliseconds, the useQuery hook will automatically refetch data from the backend at that interval, enabling real-time data updates in the front end.
const { data } = useQuery({
queryKey: ['product'],
queryFn: () => fetch( url ).then( res => res.json() ),
refetchInterval:3000,
})
Watch the video below to see how useQuery
works with refetchInterval
option
How to use UseQuery for Background data fetching
While the refetchInterval property enabled data refetching , there is one limitation to this property. That is it will refetch data as long as the browser window is active. If the browser window is not active, useQuery will stop fetching data. What if you want to refech data even when the browser window is not active?
useQuery offers another solution for this. That is refetchIntervalInBackground
property. The correct default value for refetchIntervalInBackground in the useQuery hook is false
, which means that by default, the hook will not refetch data in the background at the specified interval when the browser window is not active.
If you want to change this behavior and have the hook continue to refetch data in the background, you can set refetchIntervalInBackground
to true
.
The following video shows how to test this property.
Data transformation with “select” option in useQuery hook
You can use the select option to transform or select a part of the data returned by the query function. In the select option, you can define a function to transform the returned data of the useQuery hook. But, this select function does not affect what gets stored in the query cache. In other words, when you use the select option, UseQuery will still fetch the data from the API using the queryKey
and queryF
n options that you specify. Once the data is fetched, the select function is applied to the data and the trans
const { data } = useQuery({
queryKey: ['product'],
queryFn: () => fetch( url ).then( res => res.json() ),
select: ( data ) => data.map( e => e.name )
})
In the above code, the select option changes what is returned to the Component. The component can now use only the name of the product. However, the cache has both the product id, name, and price.
Note: Because the select option influences the returned data, you need might need to change how you access data inside the return statement in the React Component
For example:
Without select
option:
return(<div> { data?.map(( product, key ) => <li key={ key }>{ product.name }</li> )}</div> )
If you add the select option below
select:( data ) => data.map( element => element.name )
Because the map function returns an array of names( of the products ), you need to change the return a statement of the Component as below
return(<div> { data?.map(( product, key ) => <li key={ key }>{ product }</li> )}</div>
However, this largely depends on the code of your application. For example, if I add the following function in the select option I do not need to do any changes inside the return statement.
select:( data ) => data.map( element => { return {name: element.name } } )
In the above code snippet, the map function returns an array of objects with “name” as the key and the name of the product as the value. Therefore, I do not need to do any changes in my code in the return statement.
Wrapping Up
React-Query’s useQuery
hook provides several powerful options that can help you build flexible and efficient data-fetching solutions in your React applications. Whether you need to poll an API at a regular interval, fetch data in the background, or transform the data before it’s returned to the component, options like refetchInterval, refetchIntervalInBackground, and select make it easy to get the job done. By using these options in different ways, you can create data-fetching solutions that meet the specific needs of your application.
Resources
Note: In my demo project, I utilize a mock API I created with mockapi.io. However, I highly recommend creating your own API endpoint with mockapi.io. This is because it can be easier for you to do your experiment while you are learning.