#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:

  1. Declarative Data Fetching:
    • Handles entire fetch lifecycle based on query keys and fetch functions.
  2. Automatic Caching:
    • Stores query results and serves cached data while refetching in background.
  3. Smart Refetching:
    • Automatically refetches based on window focus, network reconnection, and configured intervals.

Why It Matters:


How to Implement:

  1. Basic Query Setup:
    • const { data, isLoading, error } = useQuery(['queryKey'], fetchFunction);
  2. Configure Behavior:
    • useQuery(['key'], fetchFn, { staleTime, cacheTime, refetchInterval });
  3. Manual Refetching:
    • const { refetch } = useQuery(...); // Call refetch() when needed

Example:

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 (


{data.name}




);
}
```

Connections:


References:

  1. Primary Source:
    • TanStack Query (React Query) Documentation
  2. Additional Resources:

Tags:

#React #ReactQuery #useQuery #DataFetching #Caching #AsyncState


Sources: