DEV Community

Cover image for React + TanStack Query: A Killer Combo for Data Fetching
anshit
anshit

Posted on

React + TanStack Query: A Killer Combo for Data Fetching

🧠 Why TanStack Query?

If you're tired of writing repetitive useEffect + fetch code in React, TanStack Query might just be your new best friend.

It makes data fetching, caching, pagination, and background syncing a breeze β€” and it works with any REST or GraphQL API.

In this guide, you'll learn how to use TanStack Query in a real React app to fetch and display user data.


πŸš€ What We'll Build

We’ll build a small React app that:

  • Fetches data from an API
  • Uses TanStack Query to manage the fetch
  • Handles loading and error states

🧱 Setup: Create a React App

Open your terminal and run:

npx create-react-app react-tanstack-demo
cd react-tanstack-demo
npm install @tanstack/react-query
Enter fullscreen mode Exit fullscreen mode

🌐 Wrap Your App with QueryClientProvider

Before using TanStack Query, wrap your entire app with QueryClientProvider in index.js:

// index.js
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <QueryClientProvider client={queryClient}>
      <App />
    </QueryClientProvider>
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

πŸ“¦ Create a Component That Fetches Data

Now let’s use TanStack Query to fetch user data from an API.

Update your App.js:

// App.js
import React from 'react';
import { useQuery } from '@tanstack/react-query';

const fetchUsers = async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  if (!res.ok) {
    throw new Error('Network response was not ok');
  }
  return res.json();
};

function App() {
  const { data, isLoading, error } = useQuery(['users'], fetchUsers);

  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error fetching users</p>;

  return (
    <div style={{ padding: '1rem' }}>
      <h1>User List</h1>
      <ul>
        {data.map((user) => (
          <li key={user.id}>
            <strong>{user.name}</strong> – {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

βœ… What You Learned

  • How to set up TanStack Query in a React app
  • How to fetch and cache data efficiently
  • How to handle loading and error states

🧠 Bonus: Why Use TanStack Query?

TanStack Query simplifies:

  • Caching and background refetching
  • Infinite scroll and pagination
  • Server state management It's a powerful tool for apps that deal with remote data.

πŸ™Œ Final Thoughts

TanStack Query helps you write cleaner and more scalable code. It's especially great for React developers who are tired of juggling useEffect, loading states, and manual caching.

If this helped you, follow me for more posts on React, Next.js, AWS, Vite, and other dev tools. Got questions? Drop them in the comments! πŸ’¬

πŸ’¬

πŸ‘‹ Thanks for reading β€” and happy coding!

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.