Blog>
Snippets

Configuring Stale Time and Cache Time

Illustrate how to configure `staleTime` and `cacheTime` for a query, controlling the re-fetch behavior and the duration data remains cached in React Query.
import { useQuery } from 'react-query';

function fetchPosts() {
  // Replace with actual data fetching logic
  return fetch('https://api.example.com/posts').then(res => res.json());
}

function PostsComponent() {
  const { data, isLoading } = useQuery('posts', fetchPosts, {
    staleTime: 5 * 60 * 1000, // Data is fresh for 5 minutes
    cacheTime: 15 * 60 * 1000, // Data remains in cache for 15 minutes
  });

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      {data.map(post => (
        <p key={post.id}>{post.title}</p>
      ))}
    </div>
  );
}
This code example shows how to use `useQuery` from React Query to fetch data for posts. It configures the `staleTime` to 5 minutes, meaning the fetched data will be considered fresh for this duration and won't be refetched if queried again. The `cacheTime` is set to 15 minutes, indicating how long the data should stay in the cache before being garbage collected if it's not used.