Blog>
Snippets

Implementing React Query Caching

Demonstrate how to leverage React Query's caching mechanism to prevent redundant server requests, showcasing a scenario where user data is fetched and cached for optimal performance.
import { QueryClient, QueryClientProvider, useQuery } from 'react-query';
Import necessary functions and providers from React Query.
const queryClient = new QueryClient();
Create a new QueryClient instance to manage queries and caching.
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Users />
    </QueryClientProvider>
  );
}
Wrap your application's top level component with the QueryClientProvider and pass the queryClient instance.
const fetchUsers = async () => {
  const response = await fetch('/api/users');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
};
Define a function 'fetchUsers' to fetch user data asynchronously from your API.
function Users() {
  const { data, error, isLoading } = useQuery('users', fetchUsers);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;

  return (
    <div>
      <h1>Users</h1>
      <ul>
        {data.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}
Use the useQuery hook to automatically fetch, cache, and manage user data. Display the data or loading/error states accordingly.