CodeBlanks Logo Icon CodeBlanks

React Query basics

Learn to manage server state with React Query.

What is React Query?

React Query is a library that manages server state. You fetch data with useQuery; caching, retries and synchronisation come automatically.

Each query is identified by a unique queryKey. Calls with the same key share the cache, which cuts redundant requests.

React Query wraps the app with QueryClientProvider so every component shares one cache.

The useQuery call

useQuery takes two parameters: a queryKey array and a queryFn. The return value exposes data, isLoading, error and isFetching.

The queryKey is an array; for instance ['products'] or ['product', id]. When the key changes, the query reruns automatically.

React Query deduplicates queries with the same key; if five components ask for the same data, only one request fires.

Practice UserList with useQuery

Complete the skeleton. Write a UserList component. Call useQuery with queryKey ['users'] and queryFn () => fetch('/api/users').then(r => r.json()). If isLoading render <p>Loading</p>, otherwise render <ul> with users.map(u => <li key={u.id}>{u.name}</li>). Add export default.

Starter code

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

// Write UserList here

Sample solution

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

function UserList() {
  const { data: users, isLoading } = useQuery({
    queryKey: ['users'],
    queryFn: () => fetch('/api/users').then((r) => r.json()),
  });
  if (isLoading) return <p>Loading</p>;
  return <ul>{users.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}

export default UserList;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does React Query manage?

App.jsx
It caches data coming from the server.
  • Only form state
  • Server state Correct answer
  • Only local state
  • Only CSS state

Explanation: React Query manages server state.

2 queryKey structure

Question
useQuery({ queryKey: ['product', ____], queryFn: () => fetchProduct(id) });
Answer
useQuery({ queryKey: ['product', id], queryFn: () => fetchProduct(id) });

Explanation: id adds a parameter to the queryKey.

3 React Query basics: match the terms

Term Meaning
queryKey Query identity
queryFn Fetcher function
data Returned data
isLoading First load

All lessons in Advanced