React Query tutorial code using useQuery next to a rendered list of users

React Query tutorial projects are the fastest way to see why so many React teams stopped writing their own loading flags, cache objects and retry logic. This walkthrough builds a small user directory with TanStack Query v5, from installation to the first mutation, so every concept appears in working code.

You only need a React 18 or newer project and a terminal. Each step adds one idea: the client, the provider, a query, a query key with variables, and a mutation that refreshes cached data. By the end you will understand the pattern used in real production applications.

Setting Up the Project

Any React toolchain works, but Vite keeps the setup short. Create a project, move into the folder and add the library with the package manager you prefer. The installation article covers Yarn, pnpm and Bun in more detail.

Terminal
npm create vite@latest users-app -- --template react
cd users-app
npm install @tanstack/react-query

Creating the QueryClient

The QueryClient owns the cache. Create one instance outside your components so it survives re-renders, then pass it to QueryClientProvider at the top of the tree. Every hook below the provider reads from and writes to that same cache.

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

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById('root')).render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

Fetching Data With useQuery

A query needs two things: a unique key and a function that returns a promise. The key identifies the data in the cache, while the function performs the request. React Query calls the function, stores the result and re-renders every component that observes the key.

Users.jsx
async function fetchUsers() {
  const res = await fetch('https://jsonplaceholder.typicode.com/users');
  if (!res.ok) throw new Error('Could not load users');
  return res.json();
}

export function Users() {
  const { data, isPending, isError, error } = useQuery({
    queryKey: ['users'],
    queryFn: fetchUsers,
  });

  if (isPending) return <p>Loading users…</p>;
  if (isError) return <p>{error.message}</p>;
  return <ul>{data.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}

Reading the Query State

The hook returns more than data. Status flags describe exactly where the request stands, which removes the need for separate useState calls. The most useful values are listed below.

PropertyMeaning
isPendingNo data is in the cache yet
isErrorThe last attempt failed after retries
isSuccessData is available
isFetchingA request is running, including background refetches
errorThe error thrown by the query function

Adding Variables to Query Keys

Real screens depend on input, such as a selected user. Put every variable the query function uses inside the key. When the variable changes, React Query treats it as a different cache entry and fetches it automatically, while earlier entries stay cached for quick revisits.

UserDetails.jsx
function useUser(userId) {
  return useQuery({
    queryKey: ['users', userId],
    queryFn: () => fetchUser(userId),
    enabled: Boolean(userId),
  });
}

Controlling Freshness

Fetched data is considered stale immediately by default, so the library refetches it when a component mounts again or the window regains focus. Setting staleTime tells React Query how long the data can be trusted. A directory that rarely changes can safely use a minute or more.

  • Use staleTime to reduce repeated requests for slow-changing data.
  • Keep the default for data that must always be current.
  • Read the caching explanation for the full lifecycle.

Updating Data With useMutation

Queries read data, while mutations change it. The useMutation hook wraps a function that creates, updates or deletes something on the server. After success, invalidate the related query so the list refetches and shows the new record.

AddUser.jsx
const queryClient = useQueryClient();

const addUser = useMutation({
  mutationFn: (newUser) => api.post('/users', newUser),
  onSuccess: () => {
    queryClient.invalidateQueries({ queryKey: ['users'] });
  },
});

<button onClick={() => addUser.mutate({ name: 'Ada' })}
  disabled={addUser.isPending}>Add user</button>

Handling Errors and Retries

Failed queries are retried three times on the client with an increasing delay before isError becomes true. Mutations do not retry by default, because repeating a write can create duplicates. Both behaviors are configurable through the retry option per hook or globally in defaultOptions.

Inspecting the Cache

Adding the DevTools package during development shows every query key, its status and its data. Watching keys move from fresh to stale makes the caching rules much easier to understand. The DevTools article explains each panel.

Common Mistakes Beginners Make

Most early problems come from a few habits carried over from manual fetching. Avoiding them keeps the cache predictable and the code short.

  • Creating the QueryClient inside a component, which resets the cache on every render.
  • Leaving variables out of the query key, which shows stale data for the wrong item.
  • Copying query data into useState instead of reading it from the hook.
  • Forgetting to throw when fetch returns a failed HTTP status.

Organizing Queries in Custom Hooks

Calling useQuery directly inside every component works, but repeating keys and fetchers in many files invites typos. Wrapping each query in a small custom hook keeps the key, the function and the default options in one place, so every screen requests the data in exactly the same way.

Custom hooks also make refactoring painless. When an endpoint changes, you update one file instead of hunting through components. Teams often group these hooks by feature folder, such as users, products or orders, which mirrors the structure of their query keys.

Building a Key Factory

A key factory is a plain object that produces query keys for a feature. It prevents mismatched keys between queries and invalidation calls, which is a common source of stale screens in growing applications.

queryKeys.js
export const userKeys = {
  all: ['users'],
  detail: (id) => ['users', id],
};

Testing Components That Use Queries

Tests should create a fresh QueryClient for each case and turn retries off, otherwise failing requests wait through several retry delays. Wrap the component under test in a provider that uses this client, and mock the network layer rather than the hooks themselves.

Where to Go After the Basics

With queries and mutations working, the next skills are pagination, prefetching and optimistic updates. Each builds on the same keys and client you created here, so the learning curve stays gentle. Server rendering with Next.js adds hydration, which moves the first fetch to the server for faster initial pages.

React Query Tutorial FAQ

Do I need Redux to follow this tutorial?

No. React Query handles server data on its own, and plain React state covers local interface values. The React Query vs Redux comparison explains when both make sense together.

Which React version is required?

TanStack Query v5 requires React 18 or later. Older projects on React 17 need an earlier major version of the library.

Can I use Axios instead of fetch?

Yes. The query function can call any promise-based client, including Axios or a GraphQL client, as long as it returns data or throws an error.

Conclusion

React Query tutorial steps always follow the same rhythm: create a client, wrap the app, describe data with keys and let hooks handle the rest. That pattern scales from a single list to large dashboards without extra boilerplate.

Continue with the paginated product example to see placeholder data and prefetching in action, then review the v5 changes if you maintain older code.