React Query is a powerful library for managing server state in React applications, helping optimize data fetching and updates from the server. Following Part 1’s basic introduction, this article continues with advanced features of React Query.
1. Caching – Advanced React Query Feature
React Query automatically caches data to reduce unnecessary requests. You can configure the cache duration with the cacheTime
property:
javascriptCopy codeconst { data } = useQuery({
queryKey: ['repoData'],
queryFn: fetchRepoData,
cacheTime: 1000 * 60 * 5, // Cache data for 5 minutes
});
Caching helps save resources and improves application performance when using React Query.
2. Revalidation – Advanced React Query Feature
React Query keeps data up-to-date through various refresh options, such as:
refetchOnWindowFocus
: Auto-refreshes when the user returns to the tab.refetchInterval
: Periodic refresh.refetchOnReconnect
: Refreshes when the network connection is restored.
javascriptCopy codeconst { data } = useQuery({
queryKey: ['repoData'],
queryFn: fetchRepoData,
refetchOnWindowFocus: true,
refetchInterval: 1000 * 60, // Every 60 seconds
});
3. Stale-While-Revalidate – Advanced React Query Feature
Stale-While-Revalidate allows cached data to be displayed while new data is being fetched. The staleTime
property defines the duration for which data is considered “fresh”:
javascriptCopy codeconst { data } = useQuery({
queryKey: ['repoData'],
queryFn: fetchRepoData,
staleTime: 1000 * 60 * 5, // Data remains fresh for 5 minutes
});
4. Pagination – Advanced React Query Feature
React Query supports pagination using dynamic queryKey
variables, making it easier to manage paginated data:
javascriptCopy codeconst { data, isFetching } = useQuery(['repoData', page], () => fetchRepoData(page));
5. Prefetching – Fetching Data in Advance
Prefetching allows you to load data in advance, enhancing the experience when users navigate to other pages or view details:
javascriptCopy codequeryClient.prefetchQuery(['repoData'], fetchRepoData);
6. Manual Refetch – Refreshing Data Manually
React Query provides a way for users to refresh data manually using the refetch
method:
javascriptCopy codeconst { data, refetch } = useQuery(['repoData'], fetchRepoData);
return (
<button onClick={() => refetch()}>Refresh Data</button>
);
7. Optimistic Updates
Optimistic updates display the result immediately without waiting for the server response. If the update fails, the cache is restored to its previous state:
javascriptCopy codeconst mutation = useMutation(updateData, {
onMutate: async (newData) => {
await queryClient.cancelQueries(['repoData']);
const previousData = queryClient.getQueryData(['repoData']);
queryClient.setQueryData(['repoData'], (oldData) => ({ ...oldData, ...newData }));
return { previousData };
},
onError: (err, newData, context) => {
queryClient.setQueryData(['repoData'], context.previousData);
},
onSettled: () => {
queryClient.invalidateQueries(['repoData']);
},
});
8. Retries – Retrying on Failure
You can configure retry attempts and delay between attempts when requests fail using the retry
property:
javascriptCopy codeconst { data, error, isError } = useQuery(['repoData'], fetchRepoData, {
retry: 3, // Maximum of 3 attempts
retryDelay: 2000, // Wait 2 seconds between attempts
});
9. Query Cancellation
The query cancellation feature reduces resource usage when users change actions before a request is completed:
javascriptCopy codeconst { data, isFetching } = useQuery(['repoData'], fetchRepoData);
useEffect(() => {
if (isFetching) {
queryClient.cancelQueries(['repoData']);
}
}, [isFetching]);
10. Server-Side Rendering (SSR)
React Query supports SSR, ideal for applications like Next.js to preload data on the server:
javascriptCopy codeexport async function getServerSideProps() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery(['repoData'], fetchRepoData);
return { props: { dehydratedState: dehydrate(queryClient) } };
}
11. Query Selectors – Filtering Data from Cache
With the select
property, you can filter or transform data before using it:
javascriptCopy codeconst { data } = useQuery(['repoData'], fetchRepoData, {
select: (data) => data.name, // Only retrieve the repository name
});
Conclusion
React Query offers various advanced features that enhance server-state management, particularly for complex tasks like caching, revalidation, and SSR. This helps developers optimize performance and create better user experiences in React applications.