Here's a detailed comparison of React Query vs. regular React with fetch, with 10 code examples highlighting key differences:
1. Basic Data Fetching
Regular React with Fetch
jsx Copy code
function UserProfile() {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch('https://api.example.com/user')
.then(res => {
if (!res.ok) throw new Error('Failed');
return res.json();
})
.then(data => {
setUser(data);
setLoading(false);
})
.catch(err => {
setError(err);
setLoading(false);
});
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>{user.name}</div>;
}
React Query
jsx Copy code
import { useQuery } from 'react-query';
function UserProfile() {
const { data, isLoading, isError, error } = useQuery(
'user',
() => fetch('https://api.example.com/user').then(res => {
if (!res.ok) throw new Error('Failed');
return res.json();
})
);
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error: {error.message}</div>;
return <div>{data.name}</div>;
}
2. Loading States with Skeleton UI
Regular React with Fetch
jsx Copy code
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch('https://api.example.com/users')
.then(res => res.json())
.then(data => {
setUsers(data);
setLoading(false);
});
}, []);
if (loading) return <div className="skeleton">Loading...</div>;
return <ul>{users.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}
React Query
jsx Copy code
function UserList() {
const { data, isLoading } = useQuery('users',
() => fetch('https://api.example.com/users').then(res => res.json()),
{ staleTime: 60000 } // 1 minute cache validity
);
if (isLoading) return <div className="skeleton">Loading...</div>;
return <ul>{data.map(user => <li key={user.id}>{user.name}</li>)}</ul>;
}
3. Error Handling with Retry
Regular React with Fetch
jsx Copy code
function UserProfile() {
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const [retryCount, setRetryCount] = useState(0);
useEffect(() => {
fetch('https://api.example.com/user')
.then(res => {
if (!res.ok) throw new Error('Failed');
return res.json();
})
.then(setUser)
.catch(setError);
}, [retryCount]);
if (error) return (
<div>
<p>Error: {error.message}</p>
<button onClick={() => setRetryCount(c => c + 1)}>Retry</button>
</div>
);
// ... render user
}
React Query
jsx Copy code
function UserProfile() {
const { data, error, retry } = useQuery(
'user',
() => fetch('https://api.example.com/user').then(res => {
if (!res.ok) throw new Error('Failed');
return res.json();
}),
{ retry: 3 } // Auto-retry 3 times
);
if (error) return (
<div>
<p>Error: {error.message}</p>
<button onClick={retry}>Retry</button>
</div>
);
// ... render user
}
4. Pagination
Regular React with Fetch
jsx Copy code
function UserList() {
const [page, setPage] = useState(1);
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
setLoading(true);
fetch(`https://api.example.com/users?page=${page}`)
.then(res => res.json())
.then(data => {
setUsers(data);
setLoading(false);
});
}, [page]);
return (
<div>
<button onClick={() => setPage(p => p - 1)}>Previous</button>
<button onClick={() => setPage(p => p + 1)}>Next</button>
{loading ? <div>Loading...</div> : <ul>{users.map(...)}</ul>}
</div>
);
}
React Query
jsx Copy code
function UserList() {
const [page, setPage] = useState(1);
const { data, isLoading } = useQuery(
['users', page],
() => fetch(`https://api.example.com/users?page=${page}`).then(res => res.json()),
{ keepPreviousData: true } // Maintain previous data during loading
);
return (
<div>
<button onClick={() => setPage(p => p - 1)} disabled={isLoading}>Previous</button>
<button onClick={() => setPage(p => p + 1)} disabled={isLoading}>Next</button>
{isLoading ? <div>Loading...</div> : <ul>{data.map(...)}</ul>}
</div>
);
}
5. Mutations
Regular React with Fetch
jsx Copy code
function AddUser() {
const [name, setName] = useState('');
const [mutating, setMutating] = useState(false);
const [success, setSuccess] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setMutating(true);
try {
await fetch('https://api.example.com/users', {
method: 'POST',
body: JSON.stringify({ name }),
});
setSuccess(true);
} catch (err) {
// Handle error
} finally {
setMutating(false);
}
};
return (
<form onSubmit={handleSubmit}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button disabled={mutating}>
{mutating ? 'Adding...' : 'Add User'}
</button>
{success && <div>User added!</div>}
</form>
);
}
React Query
jsx Copy code
import { useMutation } from 'react-query';
function AddUser() {
const [name, setName] = useState('');
const mutation = useMutation(
(newUser) =>
fetch('https://api.example.com/users', {
method: 'POST',
body: JSON.stringify(newUser),
}).then(res => res.json()),
{
onSuccess: () => {
queryClient.invalidateQueries('users');
}
}
);
return (
<form onSubmit={(e) => {
e.preventDefault();
mutation.mutate({ name });
}}>
<input value={name} onChange={(e) => setName(e.target.value)} />
<button disabled={mutation.isLoading}>
{mutation.isLoading ? 'Adding...' : 'Add User'}
</button>
{mutation.isSuccess && <div>User added!</div>}
</form>
);
}
6. Dependent Queries
Regular React with Fetch
jsx Copy code
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
const [posts, setPosts] = useState([]);
useEffect(() => {
// Fetch user first
fetch(`https://api.example.com/users/${userId}`)
.then(res => res.json())
.then(data => {
setUser(data);
// Then fetch posts
return fetch(`https://api.example.com/users/${userId}/posts`);
})
.then(res => res.json())
.then(setPosts);
}, [userId]);
// ... render
}
React Query
jsx Copy code
function UserProfile({ userId }) {
const { data: user } = useQuery(
['user', userId],
() => fetch(`https://api.example.com/users/${userId}`).then(res => res.json()),
{ enabled: !!userId }
);
const { data: posts } = useQuery(
['posts', userId],
() => fetch(`https://api.example.com/users/${userId}/posts`).then(res => res.json()),
{ enabled: !!user } // Only run if user data exists
);
// ... render
}
7. Auto-Refetching on Interval
Regular React with Fetch
jsx Copy code
function LiveData() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = () => {
fetch('https://api.example.com/live')
.then(res => res.json())
.then(setData);
};
fetchData();
const interval = setInterval(fetchData, 5000);
return () => clearInterval(interval);
}, []);
// ... render
}
React Query
jsx Copy code
function LiveData() {
const { data } = useQuery(
'liveData',
() => fetch('https://api.example.com/live').then(res => res.json()),
{ refetchInterval: 5000 } // Auto-refetch every 5 seconds
);
// ... render
}
8. Request Cancellation
Regular React with Fetch
jsx Copy code
function SearchResults({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
const abortController = new AbortController();
fetch(`https://api.example.com/search?q=${query}`, {
signal: abortController.signal
})
.then(res => res.json())
.then(setResults);
return () => abortController.abort();
}, [query]);
// ... render
}
React Query
jsx Copy code
function SearchResults({ query }) {
const { data } = useQuery(
['search', query],
() => fetch(`https://api.example.com/search?q=${query}`).then(res => res.json()),
{
enabled: !!query,
staleTime: 60000 // 1 minute cache validity
}
);
// React Query automatically cancels previous requests when query key changes
}
9. Caching Behavior
Regular React with Fetch
jsx Copy code
// No built-in caching - will refetch every time component mounts
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
fetch(`https://api.example.com/users/${userId}`)
.then(res => res.json())
.then(setUser);
}, [userId]); // Fetches fresh data every time
// ... render
}
React Query
jsx Copy code
// Automatic caching - data persists between renders
function UserProfile({ userId }) {
const { data } = useQuery(
['user', userId],
() => fetch(`https://api.example.com/users/${userId}`).then(res => res.json())
);
// Subsequent renders with same userId use cached data
}
10. Query Invalidation after Mutation
Regular React with Fetch
jsx Copy code
function AddUser() {
const [users, setUsers] = useState([]);
const handleAddUser = async () => {
await fetch('https://api.example.com/users', { method: 'POST' });
// Manual refetch needed
const newUsers = await fetch('https://api.example.com/users').then(res => res.json());
setUsers(newUsers);
};
// ... render
}
React Query
jsx Copy code
function AddUser() {
const mutation = useMutation(
() => fetch('https://api.example.com/users', { method: 'POST' }),
{
onSuccess: () => {
queryClient.invalidateQueries('users'); // Auto-refresh
}
}
);
// ... render
}
Key Differences Highlighted:
Caching : React Query automatically caches data
Loading States : Built-in isLoading/isFetching states
Error Handling : Simplified error management
Automatic Refetching : Interval-based and stale-while-revalidate patterns
Request Deduplication : Prevents duplicate requests
Mutation Invalidation : Clean cache management after writes
Dependent Queries : Built-in query dependency management
Retry Logic : Configurable retry mechanisms
Optimistic Updates : Easier to implement with mutation callbacks
DevTools : Built-in debugging capabilities
React Query reduces boilerplate while providing more sophisticated data-fetching patterns out of the box.