Automatic Refetching and Background Updates with TanStack Query
TanStack Query makes data synchronization effortless by supporting automatic refetching and background updates. These features ensure your application always has up-to-date data, improving user experience and maintaining data consistency.
In this tutorial, we will explore:
- How automatic refetching works.
- Configuring refetch intervals.
- Background updates on window focus and network reconnect.
- Practical examples for implementing these features.
Step 1: Setting Up TanStack Query
Install TanStack Query
npm install @tanstack/react-query
npm install @tanstack/react-query-devtools
Set Up Query Client
Wrap your app in a QueryClientProvider to enable TanStack Query.
App.js
import React from 'react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
import { UsersList } from './UsersList';
const queryClient = new QueryClient();
function App() {
return (
<QueryClientProvider client={queryClient}>
<h1>Automatic Refetching with TanStack Query</h1>
<UsersList />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
);
}
export default App;
Step 2: Enable Automatic Refetching
Automatic refetching refreshes your query’s data at regular intervals.
Example: Fetching Users with Refetch Interval
Use the refetchInterval option in the useQuery hook.
UsersList.js
import React from 'react';
import { useQuery } from '@tanstack/react-query';
const fetchUsers = async () => {
const response = await fetch('https://jsonplaceholder.typicode.com/users');
if (!response.ok) throw new Error('Failed to fetch users');
return response.json();
};
export function UsersList() {
const { data, isLoading, isError, error } = useQuery(['users'], fetchUsers, {
refetchInterval: 5000, // Refetch every 5 seconds
});
if (isLoading) return <p>Loading users...</p>;
if (isError) return <p>Error: {error.message}</p>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Step 3: Refetch on Window Focus
TanStack Query can automatically refetch data when the browser window regains focus. This ensures users always see the latest data.
Example: Refetch on Focus
Enable refetchOnWindowFocus in the query options.
UsersList.js
export function UsersList() {
const { data, isLoading, isError, error } = useQuery(['users'], fetchUsers, {
refetchOnWindowFocus: true, // Default is true
});
if (isLoading) return <p>Loading users...</p>;
if (isError) return <p>Error: {error.message}</p>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Step 4: Refetch on Network Reconnect
You can configure TanStack Query to refetch data when the network connection is restored.
Example: Refetch on Reconnect
Enable refetchOnReconnect in the query options.
UsersList.js
export function UsersList() {
const { data, isLoading, isError, error } = useQuery(['users'], fetchUsers, {
refetchOnReconnect: true, // Default is true
});
if (isLoading) return <p>Loading users...</p>;
if (isError) return <p>Error: {error.message}</p>;
return (
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
}
Step 5: Background Updates While Showing Stale Data
TanStack Query supports stale-while-revalidate, where stale data is displayed while new data is fetched in the background.
Example: Stale Time Configuration
Set staleTime to define how long the data remains fresh.
UsersList.js
export function UsersList() {
const { data, isFetching, isError, error } = useQuery(['users'], fetchUsers, {
staleTime: 10000, // Data remains fresh for 10 seconds
});
if (isError) return <p>Error: {error.message}</p>;
return (
<div>
{isFetching && <p>Updating in the background...</p>}
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
Step 6: Combining Options for Comprehensive Updates
Combine refetchInterval, refetchOnWindowFocus, refetchOnReconnect, and staleTime for a robust data synchronization strategy.
Example: Comprehensive Configuration
export function UsersList() {
const { data, isLoading, isError, error, isFetching } = useQuery(['users'], fetchUsers, {
refetchInterval: 10000, // Refetch every 10 seconds
refetchOnWindowFocus: true, // Refetch when window regains focus
refetchOnReconnect: true, // Refetch on network reconnect
staleTime: 5000, // Data remains fresh for 5 seconds
});
if (isLoading) return <p>Loading users...</p>;
if (isError) return <p>Error: {error.message}</p>;
return (
<div>
{isFetching && <p>Fetching new data...</p>}
<ul>
{data.map((user) => (
<li key={user.id}>{user.name}</li>
))}
</ul>
</div>
);
}
Best Practices
Set Appropriate Intervals:
- Use shorter intervals for frequently changing data.
- Use longer intervals for less dynamic data.
- Avoid Excessive Refetching:
- Ensure refetching doesn’t overload your server or degrade performance.
Combine Strategies:
Use refetchOnWindowFocus and refetchOnReconnect with a staleTime to balance freshness and efficiency.
In this tutorial, you learned:
- How to enable automatic refetching with intervals.
- How to refetch data on window focus and network reconnect.
- How to configure background updates with stale data.
These features make TanStack Query an excellent choice for keeping data up-to-date in modern web. Hope this is helpful, and I apologize if there are any inaccuracies in the information provided.
Comments
Post a Comment