Blog>
Snippets

Optimizing with Query Caching

Show how to configure the useQuery hook to leverage React Query's caching capabilities to avoid unnecessary network requests when the same data is requested multiple times.
import { useQuery } from 'react-query';
import axios from 'axios';
First, import useQuery from react-query and axios for making HTTP requests.
const fetchPosts = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/posts');
  return data;
};
Define an asynchronous function to fetch data using axios. This function can be any data fetching function that returns a promise.
const { data, isError, isLoading, isFetching } = useQuery('posts', fetchPosts, {
  cacheTime: 1000 * 60 * 5, // 5 minutes
  staleTime: 1000 * 60 * 1, // 1 minute
});
Use the useQuery hook to fetch data with a unique key 'posts'. Configure caching with cacheTime and staleTime options. cacheTime defines how long the cache is valid, and staleTime defines how fresh the data needs to be before fetching again.
if (isLoading || isFetching) return <div>Loading...</div>;
if (isError) return <div>Error fetching data</div>;
Handle loading and error states by checking isLoading, isFetching, and isError. Display appropriate messages based on the state.
return (
  <ul>{data.map(post => <li key={post.id}>{post.title}</li>)}</ul>
);
Render the data onto the UI by mapping over the data array. This example assumes a list of posts is being fetched.