Data Fetching in Next.jswith SWR and React Query(TanStack Query)

Data Fetching in Next.js with SWR and React Query (TanStack Query)

Sep 26, 2025 |

11 minutes read

Data Fetching in Next.jswith SWR and React Query(TanStack Query)

Next.js Data Fetching Essentials

Efficient data fetching is one of the fundamental requirements for modern web applications. Whether you are building a dashboard, a social media platform, or an e-commerce site, the ability to retrieve, manage, and display data from APIs or databases in real time is critical for user experience and application performance. Next.js, a popular React framework, provides built-in data fetching strategies such as getStaticProps, getStaticPaths, and getServerSideProps. These methods allow developers to fetch data at build time or request time, making server-side rendering (SSR) and static site generation (SSG) straightforward.

However, while Next.js’s built-in data fetching methods are powerful for many use cases, they are not sufficient for dynamic client-side interactions. Modern web applications require features such as caching, background revalidation, request deduplication, and synchronization of server state with the user interface. Without these features, developers face repetitive boilerplate code, data inconsistencies, and poor user experiences. This is where libraries like SWR and React Query (now TanStack Query) become indispensable. They provide tools and hooks for client-side data fetching, making applications more responsive, efficient, and maintainable.

Problem Statement

When building Next.js applications without a dedicated client-side data fetching library, several challenges can arise:

  • Repeated Network Requests: Every time a component re-renders or a user navigates back and forth, the application may repeatedly fetch the same data, which increases latency and API load. 
  • Stale or Outdated Data: Without proper caching or revalidation, users may see outdated information, leading to inconsistent experiences. 
  • Manual State Management: Handling loading, error, and success states manually can quickly become cumbersome, especially in larger applications. 
  • Poor Route Transitions: Switching between pages or updating components often triggers unnecessary data fetching or UI flickering. 
  • Inconsistent Server State Across Components: Sharing data between components may require lifting state up unnecessarily or implementing complex state management solutions.

These issues highlight the need for a more structured, automated, and reliable approach to fetching and managing server-side data on the client side.

Challenges with the Traditional Approach

Relying solely on Next.js’s built-in data fetching methods comes with limitations, especially for dynamic and real-time applications: 

  • Manual Re-Fetching: Components often need to implement their own useEffect hooks to fetch data after initial render, resulting in boilerplate code. 
  • Server State Synchronization: Keeping UI state in sync with server state becomes challenging when multiple components depend on the same data. 
  • Limited Caching Capabilities: Built-in Next.js methods do not provide automatic caching or deduplication of network requests, which can negatively affect performance. 
  • Background Updates: Applications cannot automatically refresh data in the background without additional custom logic. 
  • Error Handling Complexity: Developers must manually handle errors and loading states for every request, increasing the potential for inconsistent user interfaces.

These challenges become more pronounced as the application scales and the number of API interactions increases. To address these, SWR and React Query provide higher-level abstractions for handling server state, reducing boilerplate, and enhancing performance.

This is How We’ve Fixed the Issue

By integrating SWR or React Query with Next.js, developers gain powerful utilities for handling server state. Both libraries provide smart caching, revalidation, and hooks for managing async data with less boilerplate. This results in more reliable and responsive applications.

Step 1: Using SWR in Next.js 

`
Install SWR: 
bash[Text Wrapping Break]npm install swr[Text Wrapping Break] 
Example usage in a Next.js component: 
javascript[Text Wrapping Break]import useSWR from 'swr';[Text Wrapping Break][Text Wrapping Break]const fetcher = (url) => fetch(url).then((res) => res.json());[Text Wrapping Break][Text Wrapping Break]export default function Profile() {[Text Wrapping Break]  const { data, error, isLoading } = useSWR('/api/user', fetcher);[Text Wrapping Break][Text Wrapping Break]  if (error) return 
Failed to load
;[Text Wrapping Break] if (isLoading) return
Loading...
;[Text Wrapping Break][Text Wrapping Break] return
Hello, {data.name}
;[Text Wrapping Break]}[Text Wrapping Break]

Step 2: Using React Query (TanStack Query) in Next.js 

Install React Query:

`
bash[Text Wrapping Break]npm install @tanstack/react-query[Text Wrapping Break] 
Set up a `QueryClientProvider` in `_app.js`: 
javascript[Text Wrapping Break]// pages/_app.js[Text Wrapping Break]import { QueryClient, QueryClientProvider } from '@tanstack/react-query';[Text Wrapping Break]import { useState } from 'react';[Text Wrapping Break][Text Wrapping Break]function MyApp({ Component, pageProps }) {[Text Wrapping Break]  const [queryClient] = useState(() => new QueryClient());[Text Wrapping Break][Text Wrapping Break]  return ([Text Wrapping Break]	[Text Wrapping Break]  	[Text Wrapping Break]	[Text Wrapping Break]  );[Text Wrapping Break]}[Text Wrapping Break][Text Wrapping Break]export default MyApp;[Text Wrapping Break] 
Example usage of React Query in a component: 
javascript[Text Wrapping Break]import { useQuery } from '@tanstack/react-query';[Text Wrapping Break][Text Wrapping Break]const fetchUser = async () => {[Text Wrapping Break]  const res = await fetch('/api/user');[Text Wrapping Break]  return res.json();[Text Wrapping Break]};[Text Wrapping Break][Text Wrapping Break]export default function Profile() {[Text Wrapping Break]  const { data, error, isLoading } = useQuery(['user'], fetchUser);[Text Wrapping Break][Text Wrapping Break]  if (error) return 
Error loading user
;[Text Wrapping Break] if (isLoading) return
Loading...
;[Text Wrapping Break][Text Wrapping Break] return
Hello, {data.name}
;[Text Wrapping Break]}

Best Practices and Recommendations 

To maximize the benefits of SWR and React Query in Next.js projects: 

1. Choose the Right Tool: 

  • Use SWR for smaller projects with simpler data fetching requirements. 
  • Use React Query for complex applications with multiple interdependent queries, paginated data, or optimistic updates. 

2. Handle Loading and Error States Gracefully: Always display a user-friendly loading indicator and error messages. 

3. Leverage Caching and Deduplication: Avoid unnecessary network requests by caching results and revalidating them in the background. 

4. Set Appropriate Stale and Cache Times: Configure staleTime and cacheTime according to the nature of the data (frequently changing data vs. mostly static). 

5. Use Query Invalidation for Dynamic Updates: When data changes on the server, invalidate relevant queries to ensure components display the latest information. 

6. Centralize API Fetch Logic: Create reusable fetcher functions to maintain consistency and reduce code duplication.

Next.js Data Fetching Made Simple and Efficient

The Way Forward

Integrating Storybook with Next.js allows developers to work on UI components independently, improves collaboration with designers and QA, and ensures a consistent and scalable component library. Following best practices can accelerate development while maintaining high-quality UI standards. 

  • Faster development cycles due to reduced dependency on application logic 
  • Improved collaboration as designers, developers, and QA work off the same interactive component library 
  • Consistent UI patterns enforced across the codebase 
  • Better documentation with living, interactive examples always in sync with the code 
  • Easier onboarding for new developers who can learn the system by browsing the Storybook 

As projects grow in complexity, Storybook evolves from being a helpful tool to an essential piece of the development workflow. It enables teams to practice true component-driven development and maintain a single source of truth for the UI.

Free Consultation

    Jignesh Jadav

    Jignesh is a recognized Assistant Project Manager at iFlair Web Technologies Pvt. Ltd. Jignesh has over 9 years of industry experience, and in his career, he has managed many web development projects that have been delivered on time with high customer satisfaction. His skills include JS expertise including Angular, React, Vue.js, Mean.js, Next.js, Nuxt.js, and Full-stack tech expertise also in project planning, client communication, and team management, which are a great addition to the company's continuous development and success in the technology industry.



    MAP_New

    Global Footprints

    Served clients across the globe from38+ countries

    iFlair Web Technologies
    Privacy Overview

    This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.