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

How to best get data from react-query cache?

1个答案

1

When using React Query, it provides a consistent and elegant approach to managing server state within frontend applications. React Query automatically caches data and enables you to retrieve it from the cache with a simple API. Here are the basic steps for React Query to retrieve data from the cache:

  1. Installing and Importing React Query: Install React Query in your project and import the relevant hooks, such as useQuery, into your components.

    bash
    npm install react-query

    Or

    bash
    yarn add react-query
  2. Using the useQuery Hook: Use the useQuery hook to initiate requests and retrieve data from the cache. useQuery requires at least two parameters: a unique cache key and an asynchronous function to fetch data.

    jsx
    import { useQuery } from 'react-query'; // Asynchronous function to fetch data const fetchData = async () => { const response = await fetch('https://api.example.com/data'); return response.json(); }; // Within a component const { data, isLoading, error } = useQuery('uniqueCacheKey', fetchData);

    In this example, 'uniqueCacheKey' serves as the cache key, identifying and storing the retrieved data. fetchData is an asynchronous function that fetches data from the server.

  3. Reading Data from the Cache: When a component calls useQuery with the same cache key, React Query first checks if matching data exists in the cache. If data is available, it immediately returns it without initiating a new network request.

    jsx
    // Another component using the same cache key const { data, isLoading, error } = useQuery('uniqueCacheKey', fetchData);
  4. Cache Updates and Expiry: React Query offers flexible cache duration and update mechanisms. For instance, you can configure data to expire after a specific time or refetch on events like window focus to ensure users always see the latest information.

    jsx
    const { data, isLoading, error } = useQuery('uniqueCacheKey', fetchData, { staleTime: 5 * 60 * 1000, // Data becomes stale after 5 minutes refetchOnWindowFocus: true // Refetch data when window regains focus });
  5. Manually Managing Cache Data: If needed, you can use React Query's queryClient methods to manually update or invalidate data associated with specific cache keys.

    jsx
    import { useQueryClient } from 'react-query'; const queryClient = useQueryClient(); // Manually invalidate cached data queryClient.invalidateQueries('uniqueCacheKey'); // Manually update cached data queryClient.setQueryData('uniqueCacheKey', updatedData);

By doing so, React Query optimizes data loading, reduces unnecessary network requests, and ensures data freshness. It effectively handles background data synchronization while minimizing the burden on developers to manually manage cache logic.

2024年6月29日 12:07 回复

你的答案