SmartCodingTips

🔍 React Query – The Data-Fetching Powerhouse

React Query (now called TanStack Query) simplifies data fetching, caching, synchronizing, and updating your server state — all without the boilerplate of useEffect and useState.


⚙️ 1. Installation


npm install @tanstack/react-query

🔧 2. Setup QueryClientProvider


import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <MyComponent />
    </QueryClientProvider>
  );
}

📦 3. Basic Fetch Example


import { useQuery } from '@tanstack/react-query';

function MyComponent() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['users'],
    queryFn: () => fetch('https://api.example.com/users').then(res => res.json())
  });

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return (
    <ul>
      {data.map(user => <li key={user.id}>{user.name}</li>)}
    </ul>
  );
}

🚀 4. Key Features

  • Built-in loading, error, and success states
  • Automatic background refetching
  • Out-of-the-box caching
  • Refetch on window focus / reconnect
  • Polling and pagination support

✏️ 5. Mutation (POST/PUT/DELETE)


import { useMutation } from '@tanstack/react-query';

const mutation = useMutation({
  mutationFn: (newUser) =>
    fetch('/users', {
      method: 'POST',
      body: JSON.stringify(newUser),
    }),
});

🛠️ 6. DevTools


import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

<ReactQueryDevtools initialIsOpen={false} />

This gives you powerful debugging features for live query inspection and mutation tracking.

✅ 7. When to Use React Query

  • Working with REST or GraphQL APIs
  • Need caching or refetching logic
  • Frequent GET requests or paginated content