🌐 React API Integration & Data Fetching
Estimated reading: 4 minutes 27 views

πŸ“¦ React Data Fetching using React Query & SWR – The 2025 Optimization Guide


🧲 Introduction – Why Use React Query or SWR?

Managing API calls with useEffect and useState works fineβ€”until it doesn’t. For apps with multiple endpoints, loading spinners, caching, pagination, and real-time updates, you’ll need a smarter data-fetching solution.

React Query and SWR offer powerful abstractions for:

  • ⚑ Caching and background updates
  • πŸ” Refetching, retrying, and invalidation
  • βœ… Simplified API logic with status tracking
  • πŸ’Ύ Automatic sync with server state

🎯 In this guide, you’ll learn:

  • What makes React Query and SWR different
  • How to fetch data with each library
  • Key features: caching, refetching, and error handling
  • Best practices for building scalable data-driven apps

βš™οΈ 1. What Are React Query and SWR?

FeatureReact Query (TanStack)SWR (Vercel)
PurposeServer-state managementData fetching & caching
API styleuseQuery, useMutationuseSWR hook
DevToolsβœ… Yes (DevTools extension)⚠️ Limited
Optimistic Updatesβœ… Full support⚠️ Manual
Pagination/Infiniteβœ… Built-in⚠️ Requires custom logic
Query invalidationβœ… Manual & automatic❌ Not built-in

πŸ“¦ 2. React Query Setup & Usage

βœ… Install:

npm install @tanstack/react-query

βœ… Wrap Your App:

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

const queryClient = new QueryClient();

<QueryClientProvider client={queryClient}>
  <App />
</QueryClientProvider>

βœ… Basic useQuery Example:

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

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

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

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

πŸ“˜ Handles loading, error, and refetching out of the box
βœ… Perfect for dashboards, filtered lists, and search UIs


🌐 3. SWR Setup & Usage

βœ… Install:

npm install swr

βœ… Basic useSWR Example:

import useSWR from 'swr';

const fetcher = (url) => fetch(url).then(res => res.json());

const { data, error, isLoading } = useSWR('/api/posts', fetcher);

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

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

βœ… Zero-config and dead-simple
βœ… Automatically revalidates on window focus and reconnect


πŸ” 4. Refetching & Revalidation

βœ… React Query:

const query = useQuery({ queryKey: ['posts'], queryFn: fetchPosts });

// Manual refetch
<button onClick={() => query.refetch()}>Refresh</button>;

βœ… SWR:

const { data, mutate } = useSWR('/api/posts', fetcher);

// Trigger revalidation
<button onClick={() => mutate()}>Refresh</button>;

πŸ“˜ mutate() can also be used for optimistic updates


πŸ”§ 5. Handling Pagination with React Query

const {
  data,
  fetchNextPage,
  hasNextPage,
  isFetchingNextPage,
} = useInfiniteQuery({
  queryKey: ['posts'],
  queryFn: ({ pageParam = 1 }) =>
    fetch(`/api/posts?page=${pageParam}`).then(res => res.json()),
  getNextPageParam: (lastPage) => lastPage.nextPage ?? false,
});

βœ… Infinite scroll + pagination = built-in
πŸ“˜ SWR requires manual implementation of pagination logic


🧠 6. React Query vs SWR – When to Use What?

Use CaseRecommended Tool
Large-scale apps, dashboardsReact Query
Simple fetch + cache (small apps)SWR
Infinite queries & mutationsReact Query
SSR/ISR with Next.jsSWR (Vercel-native)
DevTools & advanced debuggingReact Query

πŸ“˜ Best Practices

βœ… Use queryKey to scope & cache data correctly
βœ… Use staleTime and cacheTime wisely
βœ… Use suspense: true with lazy-loaded components
βœ… Use mutate or invalidateQueries to trigger refetch
βœ… Wrap logic in custom hooks (e.g., usePosts()) for reusability


πŸ“Œ Summary – Recap & Next Steps

React Query and SWR simplify and supercharge data fetching in React. They give you better caching, revalidation, and status management than manually using useEffect.

πŸ” Key Takeaways:

  • React Query = robust async state with powerful APIs
  • SWR = lightweight caching-focused data hook
  • Both handle loading/error states automatically
  • Enable features like caching, retry, refetch, and optimistic updates
  • Use for REST, GraphQL, or even local cache/mocks

βš™οΈ Real-World Relevance:
Used in production by Notion, GitHub, Hashnode, and Vercel to manage UI data with blazing-fast performance and reliability.


❓ FAQ Section

❓ Do I still need Redux with React Query or SWR?
❌ Not for async state. These tools replace Redux for most API-related state.


❓ Can React Query and SWR work with GraphQL?
βœ… Yes. Just replace the fetcher with your GraphQL request logic.


❓ What is the main difference between SWR and React Query?
βœ… SWR is minimalist and fetch-focused. React Query is feature-rich, built for large apps, with support for caching, pagination, mutations, and devtools.


❓ Can I use these in SSR or SSG apps?
βœ… Yes. SWR is optimized for Next.js. React Query also supports Hydration for SSR/SSG.


❓ Is caching automatic in these tools?
βœ… Yes. Both tools cache by default and revalidate automatically depending on config.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

πŸ“¦ React Data Fetching using React Query / SWR

Or Copy Link

CONTENTS
Scroll to Top