Blog>
Snippets

Synchronizing Data Across Components with useQuery

Explain how to use the useQuery hook within multiple components to fetch the same data while ensuring the cache is shared, resulting in a single network request and synchronized component states.
import { QueryClient, QueryClientProvider } from 'react-query';
const queryClient = new QueryClient();
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Other components will go here */}
    </QueryClientProvider>
  );
}
This code initializes a QueryClient instance and wraps the App component with QueryClientProvider, enabling React Query's features throughout the application.
import { useQuery } from 'react-query';
import axios from 'axios';
function TodoList() {
  const { isLoading, error, data } = useQuery('todos', () => axios.get('/api/todos').then(res => res.data));
  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>An error occurred: {error.message}</div>;
  return (
    <ul>{data.map(todo => <li key={todo.id}>{todo.title}</li>)}</ul>
  );
}
This component fetches a list of todos using the useQuery hook. This hook uses a cache key ('todos') to avoid multiple network requests for the same data across components.
function TodoCounter() {
  const { data } = useQuery('todos', () => axios.get('/api/todos').then(res => res.data), {
    staleTime: Infinity
  });
  return <div>Total Todos: {data?.length}</div>;
}
Another component using the same cache key ('todos') to fetch data. It shares the cache with TodoList, resulting in a single network request. The stale time is set to Infinity to prevent refetches.