How do you set up React Query in a React application?

Beginner

Answer

Setting up React Query involves three main steps:

  1. Install the package:
npm install @tanstack/react-query
  1. Create and provide QueryClient:
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app components */}
    </QueryClientProvider>
  );
}
  1. Use React Query hooks in components:
import { useQuery } from '@tanstack/react-query';
function Posts() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['posts'],
    queryFn: () => fetch('/api/posts').then(res => res.json())
  });
  if (isLoading) return 'Loading...';
  if (error) return 'Error occurred';
  return <div>{/* Render posts */}</div>;
}