Intermediate LevelReact JS & React 19
Why should you use TanStack Query (React Query) instead of useEffect for data fetching?
❓ Interview Prompt: Compare `useEffect` data fetching (boilerplate, race conditions, memory leaks, no caching) vs TanStack Query (caching, deduplication, auto-refetch, stale-while-revalidate).
Fetching data inside 'useEffect' is prone to severe bugs (race conditions, unmounted component memory leaks, missing error states, no caching).
Advantages of TanStack Query (React Query):
•
Automatic Caching: Shares and caches query data across components.
•
Stale-While-Revalidate: Renders cached data instantly while fetching fresh data in the background.
•
Deduplication: Merges duplicate concurrent network requests into a single HTTP call.
•
Automatic Refetching: Refetches data on window focus or network reconnect.
Code Implementation Example
jsx
import { useQuery } from '@tanstack/react-query';
function UserProfile({ userId }) {
// 1-liner with automatic caching, refetching, and error handling!
const { data, isLoading, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch('/api/users/${userId}').then(res => res.json())
});
if (isLoading) return <p>Loading...</p>;
if (error) return <p>Error loading user!</p>;
return <h1>{data.name}</h1>;
}💡Data fetching with automatic caching and deduplication using TanStack Query.
🎯 Interview Key Takeaway
Use TanStack Query instead of useEffect for data fetching to gain built-in caching, request deduplication, and stale-while-revalidate.
#TanStack Query#React Query#Data Fetching#Intermediate
Back to all React JS & React 19 Questions→