Below are 10 side-by-side examples that illustrate how you’d implement the same feature first with “plain” React (useState, useEffect, and fetch) and then with React Query (@tanstack/react-query).
For each case you’ll see:
• “Vanilla” React code
• React Query code
• What you gain/lose
0. Boilerplate (shared in all examples)
tsx Copy code
// main.tsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import App from './App';
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>
);
All React Query snippets assume you’ve wrapped your tree with QueryClientProvider.
1. Basic Fetch on Mount
1A — Vanilla React
tsx Copy code
// UsersPlain.tsx
import { useState, useEffect } from 'react';
export default function UsersPlain() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoad] = useState(true);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
let ignore = false;
fetch('/api/users')
.then(res => {
if (!res.ok) throw new Error('Network error');
return res.json();
})
.then(data => !ignore && setUsers(data))
.catch(err => !ignore && setError(err))
.finally(() => !ignore && setLoad(false));
return () => { ignore = true };
}, []);
if (loading) return <p>Loading...</p>;
if (error) return <p>{error.message}</p>;
return (
<ul>
{users.map(u => <li key={u.id}>{u.name}</li>)}
</ul>
);
}
1B — React Query
tsx Copy code
// UsersRQ.tsx
import { useQuery } from '@tanstack/react-query';
export default function UsersRQ() {
const { data: users, error, isLoading } =
useQuery(['users'], () =>
fetch('/api/users').then(r => r.json())
);
if (isLoading) return <p>Loading...</p>;
if (error) return <p>{(error as Error).message}</p>;
return (
<ul>
{users!.map(u => <li key={u.id}>{u.name}</li>)}
</ul>
);
}
Difference ➜ less manual state, auto-caching under the key ['users'].
2. Refetch on Focus / Window Re-open
Vanilla has no built-in answer—you’d wire up visibilitychange.
React Query: one prop.
tsx Copy code
const { data } = useQuery(['users'], fetchFn, { refetchOnWindowFocus: true })
3. Polling / Interval Refetch
3A — Vanilla
tsx Copy code
useEffect(() => {
const id = setInterval(() => {
fetch('/api/users').then(/* ... */)
}, 30_000);
return () => clearInterval(id);
}, []);
3B — React Query
tsx Copy code
useQuery(['users'], fetchFn, { refetchInterval: 30_000 });
4. Pagination
4A — Vanilla
tsx Copy code
export default function PaginatedPlain() {
const [page, setPage] = useState(1);
const [results, setRes] = useState<User[]>([]);
const [hasNext, setHasNext] = useState(false);
useEffect(() => {
setRes([]); // clear
fetch(`/api/users?page=${page}`)
.then(r => r.json())
.then(d => {
setRes(d.items);
setHasNext(d.hasNext);
});
}, [page]);
return (
<>
{results.map(u => <div key={u.id}>{u.name}</div>)}
<button disabled={!hasNext} onClick={() => setPage(p => p + 1)}>
Next
</button>
</>
)
}
4B — React Query (Infinite Query)
tsx Copy code
import { useInfiniteQuery } from '@tanstack/react-query';
export default function PaginatedRQ() {
const {
data,
hasNextPage,
fetchNextPage, // magic
isFetchingNextPage
} = useInfiniteQuery(
['users'],
({ pageParam = 1 }) =>
fetch(`/api/users?page=${pageParam}`).then(r => r.json()),
{
getNextPageParam: last => last.hasNext ? last.nextPage : undefined
}
);
return (
<>
{data?.pages.flatMap(p => p.items)
.map(u => <div key={u.id}>{u.name}</div>)}
<button disabled={!hasNextPage || isFetchingNextPage}
onClick={() => fetchNextPage()}>
{isFetchingNextPage ? 'Loading...' : 'Next'}
</button>
</>
)
}
React Query tracks “pages” and hands you helpers (hasNextPage, fetchNextPage).
5. Dependent Queries (fetch if param is ready)
5A — Vanilla
tsx Copy code
function DetailPlain({ userId }: { userId?: string }) {
const [user, setUser] = useState<User | null>(null);
useEffect(() => {
if (!userId) return;
fetch(`/api/users/${userId}`).then(r => r.json()).then(setUser);
}, [userId]);
/* ... */
}
5B — React Query
tsx Copy code
function DetailRQ({ userId }: { userId?: string }) {
const { data } = useQuery(['user', userId],
() => fetch(`/api/users/${userId}`).then(r => r.json()),
{ enabled: !!userId } // <- crucial
);
/* ... */
}
enabled acts like an early-exit.
6. POST/PUT Mutations
6A — Vanilla
tsx Copy code
async function addUser(name: string) {
await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type':'application/json' },
body: JSON.stringify({ name })
});
// then manually refetch list:
fetchUsersAgain();
}
6B — React Query
tsx Copy code
const queryClient = useQueryClient();
const mutation = useMutation(
(name: string) =>
fetch('/api/users', {
method:'POST',
headers:{'Content-Type':'application/json'},
body: JSON.stringify({ name })
}),
{
onSuccess: () => queryClient.invalidateQueries(['users'])
}
);
invalidateQueries tells React Query “my cached ['users'] is stale, please refetch.”
7. Optimistic Updates
7A — Vanilla
You’d copy list → mutate copy → setState → rollback on error (lots of boilerplate).
7B — React Query
tsx Copy code
const mutation = useMutation(
updateUser,
{
onMutate: async (updated: User) => {
await queryClient.cancelQueries(['users']);
const prev = queryClient.getQueryData<User[]>(['users']);
queryClient.setQueryData<User[]>(['users'], old =>
old!.map(u => u.id === updated.id ? { ...u, ...updated } : u)
);
return { prev }; // context for rollback
},
onError: (_err, _var, ctx) => {
queryClient.setQueryData(['users'], ctx?.prev);
},
onSettled: () => queryClient.invalidateQueries(['users'])
}
);
Optimism with rollback in ~20 lines.
8. Cache Time & Stale Time
Vanilla: you re-fetch every mount or craft a global store.
React Query:
tsx Copy code
useQuery(['users'], fetchFn, {
staleTime: 5 * 60_000, // considered “fresh” for 5 min
cacheTime: 30 * 60_000 // garbage-collected after 30 min
});
No manual timers.
9. Prefetch on Link Hover
9A — Vanilla
tsx Copy code
function LinkWithPrefetch({ id, children }: { id: string }) {
const handleMouseEnter = () => {
fetch(`/api/users/${id}`); // no caching built-in
};
return <Link to={`/users/${id}`} onMouseEnter={handleMouseEnter}>{children}</Link>
}
9B — React Query
tsx Copy code
import { useQueryClient } from '@tanstack/react-query';
function PrefetchLink({ id, children }: { id: string }) {
const qc = useQueryClient();
const onEnter = () => qc.prefetchQuery(['user', id],
() => fetch(`/api/users/${id}`).then(r => r.json())
);
return <Link to={`/users/${id}`} onMouseEnter={onEnter}>{children}</Link>
}
Data is waiting in cache when the route renders.
10. Global Error Handling & Retry
10A — Vanilla
You’d wrap fetch in a helper, maybe context, implement retries yourself.
10B — React Query
tsx Copy code
useQuery(['users'], fetchFn, {
retry: 3, // retry 3× on failure
retryDelay: attempt => attempt * 1000
});
You can also pass a global queryClient config: { defaultOptions: { queries: { retry: 2 }}}
Key Take-aways
Boilerplate: React Query erases useState + useEffect boilerplate.
Caching: Automatic, keyed, time-based, and garbage-collected.
Background refetch & window-focus refetch: built-in.
Mutations & optimistic updates feel Redux-like but without reducers.
Vanilla stays lighter (no dependency) and gives you full control, but you’ll re-write many features React Query already solved (cache, deduping, polling, retries, focus refetch, prefetch, optimistic updates…).
If you only need 1–2 fetches and no caching, plain React is OK.
For data-heavy apps, React Query pays off quickly.