Optimizing React Query Caching
Illustrate best practices in query caching with React Query to minimize network requests and improve application performance.
import { useQuery } from 'react-query';
const fetchUserData = async (userId) => {
const response = await fetch(`/api/user/${userId}`);
if (!response.ok) throw new Error('Network response was not ok.');
return response.json();
};
Defines an asynchronous function to fetch user data from an API. This function will be used with React Query's useQuery hook for fetching and caching data.
const { data, error, isLoading } = useQuery(['userData', userId], () => fetchUserData(userId), {
staleTime: 5 * 60 * 1000, // Data is fresh for 5 minutes
cacheTime: 30 * 60 * 1000, // Data is cached for 30 minutes
refetchOnWindowFocus: false
});
Utilizes the useQuery hook from React Query to fetch and cache the user data. It sets the staleTime to 5 minutes, meaning the data will not be refetched until it's considered stale after 5 minutes. The cacheTime is set to 30 minutes, indicating the cached data will be discarded if not used within 30 minutes. The 'refetchOnWindowFocus' is set to false to prevent refetching data every time the window regains focus, optimizing the application performance.
if (isLoading) return <div>Loading...</div>;
if (error) return <div>An error has occurred: {error.message}</div>;
return <div>User Name: {data.name}</div>;
Handles the loading state, error state, and successful data fetching by conditionally rendering different UI elements. Demonstrates how to access and display fetched data (in this case, the user's name) within a component.