Fetch Api Data with React Query 2025

Fetch API Data with React Query (TanStack Query) 2025

Once your app is wrapped with QueryClientProvider, you can easily fetch data using the useQuery hook from TanStack Query.

1. Basic Setup with useQuery

Here's how you can fetch API data using React Query:

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

function fetchUsers() {
  return fetch('https://jsonplaceholder.typicode.com/users').then(res => res.json());
}

function UsersComponent() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['users'],
    queryFn: fetchUsers,
  });

  if (isLoading) return 

Loading...

; if (error) return

Error fetching data

; return (
    {data.map(user => (
  • {user.name}
  • ))}
); }

2. Explanation

  • useQuery takes a queryKey and a queryFn.
  • queryKey is used for caching and tracking data.
  • queryFn is the function that performs the actual fetch.
  • isLoading and error help handle the UI state.

3. Final Output in JSX

This component will display a list of user names fetched from the API, and handle loading and error states.

With TanStack Query, you don't have to manage loading or error states manually with useEffect and useState – everything is handled efficiently.