Optimizing Queries with Stale Time
Demonstrate setting up stale time for a query to manage how often the data is refetched, reducing unnecessary network requests.
import { useQuery } from 'react-query';
function fetchData(key) {
return fetch(`https://api.example.com/data/${key}`).then(res =>
res.json()
);
}
export default function App() {
const { data, error, isLoading } = useQuery('dataKey', () => fetchData('dataKey'), {
staleTime: 5 * 60 * 1000 // 5 minutes in milliseconds
});
// Component logic here
}
This code snippet demonstrates how to use React Query's `useQuery` hook to fetch data and set a stale time of 5 minutes. The `staleTime` option tells React Query not to refetch the data if it is considered fresh, effectively reducing unnecessary network requests for a period of 5 minutes after the initial fetch.