乐闻世界logo
搜索文章和话题

How to keep previous data when refetching multiple times using React Query?

1个答案

1

In handling data with React Query, it is common to encounter scenarios where you need to maintain existing data during re-requests. React Query provides several strategies and configurations for this purpose, with one key feature being the use of staleTime and cacheTime to manage data freshness and cache duration.

Using staleTime to Maintain Data Freshness

staleTime defines the duration during which data is considered "fresh," meaning no new network requests are triggered for the same query within this period. Thus, even during multiple re-requests, as long as the data remains within the freshness window, React Query will utilize cached data instead of re-fetching.

jsx
import { useQuery } from 'react-query'; function fetchProjects() { return fetch('https://api.example.com/projects').then(res => res.json()); } function Projects() { const { data } = useQuery('projects', fetchProjects, { staleTime: 5 * 60 * 1000, // 5 minutes }); return <div>{data.map(project => <p>{project.name}</p>)}</div>; }

Using cacheTime to Control Cache Duration

Additionally, cacheTime defines how long data remains in the cache. This duration starts after the data becomes stale (i.e., after staleTime has elapsed). If a request for the same data is made within this period, React Query will still retrieve data from the cache instead of re-fetching from the network.

jsx
const { data } = useQuery('projects', fetchProjects, { staleTime: 5 * 60 * 1000, // Data freshness duration cacheTime: 30 * 60 * 1000, // Cache duration });

Continuing to Display Old Data During Requests

In React Query, when a new request is in progress, you can configure it to continue displaying old data. This is achieved by setting keepPreviousData to true, which maintains the display of the previous data until the new data is fully loaded.

jsx
const { data, isFetching } = useQuery(['projects', projectId], fetchProjects, { keepPreviousData: true, }); if (isFetching) { // Handle loading state while old data remains visible }

By leveraging these configuration options in React Query, we can effectively manage data caching and updates within applications, enhancing user experience and reducing unnecessary network requests and loading delays. These methods can be flexibly applied to accommodate various business requirements and scenarios. When using React Query, it is common to face situations where re-requesting data while preserving old data is needed. React Query provides multiple strategies for handling data updates and caching, with one highly practical feature being stale data preservation.

Using staleTime to Preserve Data

In React Query, the staleTime option in useQuery or useInfiniteQuery hooks allows you to define the duration during which data can be considered fresh (i.e., no re-fetching is needed). During this period, even if the component re-renders or the query is re-executed, React Query will directly provide data from the cache without re-fetching.

jsx
import { useQuery } from 'react-query'; import axios from 'axios'; function fetchProjects() { return axios.get('/api/projects'); } function Projects() { const { data, isError, isLoading } = useQuery('projects', fetchProjects, { staleTime: 5 * 60 * 1000, // Data freshness duration of 5 minutes }); if (isLoading) { return <div>Loading...</div>; } if (isError) { return <div>Error fetching projects</div>; } return ( <div> {data?.data.map(project => ( <p key={project.id}>{project.name}</p> ))} </div> ); }

In this example, even if the Projects component re-renders multiple times, no new requests are made within the 5-minute period; instead, cached data is used.

Background Fetching on Window Focus

React Query also provides functionality to trigger data updates when the window regains focus, achieved by setting the refetchOnWindowFocus option. This ensures users see the latest data when returning to the application window, while previous data remains available until new data is loaded, enhancing user experience.

jsx
const { data } = useQuery('todos', fetchTodos, { staleTime: 5000, refetchOnWindowFocus: true });

Data Retention and Expiration

Finally, the cacheTime option in React Query controls how long successfully queried data remains in the cache. Even if the query state becomes "inactive," this data can still be reused during the cache duration. After this period, the data is garbage collected.

jsx
const { data } = useQuery('todos', fetchTodos, { cacheTime: 10 * 60 * 1000 // Data remains in cache for 10 minutes });

Through these settings and strategies, React Query not only effectively manages data re-requests and caching but also strikes a good balance between user experience and application performance.

2024年6月29日 12:07 回复

你的答案