React Query is a powerful data-fetching library for React that simplifies managing server state, such as fetching, caching, synchronizing, and updating data in your UI.
🔹 Key Features:
- ✅ Fetch, cache, and sync server data with ease
- 🚀 Auto-updates data on window refocus or network reconnect
- 📦 Built-in caching and deduplication
- ⏱ Background refetching
- 🧠 Smart query invalidation and pagination
- ⚙ Works seamlessly with any REST or GraphQL API
🔹 Basic Example:
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';
function Users() {
const { data, isLoading, error } = useQuery({
queryKey: ['users'],
queryFn: () => axios.get('/api/users').then(res => res.data),
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error: {error.message}</p>;
return (
<ul>
{data.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
🔹 Why Use React Query?
- Removes manual handling of loading/error states
- Reduces boilerplate compared to
useEffect+useState - Keeps UI in sync with server data
- Enables auto-refetch and optimistic updates
📝 In Summary:
React Query abstracts away the complexity of data-fetching and caching in React apps, making server-state management simple, efficient, and scalable.