#atom
useQuery - Data Fetching and Caching with React Query
Core Idea:
The useQuery hook from React Query provides a declarative way to fetch, cache, and synchronize server state in React applications with built-in loading, error handling, and data staleness management.
Key Principles:
- Declarative Data Fetching:
- Handles entire fetch lifecycle based on query keys and fetch functions.
- Automatic Caching:
- Stores query results and serves cached data while refetching in background.
- Smart Refetching:
- Automatically refetches based on window focus, network reconnection, and configured intervals.
Why It Matters:
- Separation of Concerns:
- Decouples data fetching logic from component rendering.
- Performance Optimization:
- Reduces unnecessary network requests via caching.
- User Experience:
- Provides loading states and error handling out of the box.
How to Implement:
- Basic Query Setup:
const { data, isLoading, error } = useQuery(['queryKey'], fetchFunction);
- Configure Behavior:
useQuery(['key'], fetchFn, { staleTime, cacheTime, refetchInterval });
- Manual Refetching:
const { refetch } = useQuery(...); // Call refetch() when needed
Example:
-
Scenario:
- A profile page that needs to fetch user data.
-
Application:
function UserProfile({ userId }) {
const { data, isLoading, error, refetch } = useQuery(
['user', userId],
() => fetchUserById(userId),
{ staleTime: 5 * 60 * 1000 } // 5 minutes
);
if (isLoading) return
Loading...
;if (error) return
Error: {error.message}
;return (
);
}
```
- Result:
- Data is automatically fetched, cached, and refreshed with loading/error states.
Connections:
- Related React Concepts:
- useEffect: Traditional approach for data fetching.
- useMutation: Companion hook for data mutations.
- React Query
- Broader Programming Concepts:
- Caching Strategies: Optimizing data access patterns.
- Stale-While-Revalidate: Pattern for improved perceived performance.
References:
- Primary Source:
- TanStack Query (React Query) Documentation
- Additional Resources:
Tags:
#React #ReactQuery #useQuery #DataFetching #Caching #AsyncState
Sources:
- From: AG Grid