Stop Wasting Time: Handle Api Loading & Error 2025

🚫 Stop Wasting Time: Handle API Loading & Error Properly (2025)

Many React developers still handle API states manually using useEffect and useState, which leads to messy code. Let’s fix that using React Query (TanStack Query) – the modern way!

1. Problem with Traditional Method

// ❌ This is messy and repetitive
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);

useEffect(() => {
  fetch('/api/data')
    .then(res => res.json())
    .then(setData)
    .catch(setError)
    .finally(() => setLoading(false));
}, []);

2. ✅ Use React Query to Simplify

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

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

  if (isLoading) return 

⏳ Loading...

; if (isError) return

❌ Error: {error.message}

; return (
{data.map(item => (

{item.name}

))}
); }

3. Why This Is Better

  • No more manually tracking loading or error states.
  • Automatic caching, background refetching, and retry support.
  • Cleaner, readable code that scales well with your app.

🔥 Pro Tip:

Add a fallback UI using React Suspense + React Query for even better UX!

2025 is the year to stop doing things the old way. Use React Query and save hours of frustration. 🚀