TanStack Query, formerly known as React Query, is a powerful data-fetching library for React and other frameworks. It simplifies managing server state, caching, synchronizing data, and more.
Key Features :
Data Fetching: Simplifies data-fetching logic with hooks like useQuery and useMutation.
Caching: Automatically caches fetched data, minimizing redundant requests.
Synchronization: Ensures fresh data by re-fetching on focus, reconnect, or stale.
Pagination/Infinite Scroll: Supports features like pagination and infinite scroll.
Optimistic Updates: Allows for smooth UI updates while waiting for server responses.
Error Handling: Centralized error handling for network requests.
Basic Example:
jsx
import { useQuery } from '@tanstack/react-query'; import axios from 'axios'; const fetchUsers = async () => { const { data } = await axios.get('/api/users'); return data; }; function Users() { const { data, error, isLoading } = useQuery(['users'], fetchUsers); if (isLoading) return <div>Loading...</div>; if (error) return <div>Error occurred: {error.message}</div>; return ( <ul> {data.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); }
In this example:
useQuery is used to fetch user data.
It handles loading, error states, and displaying the data.
Top comments (0)