React › Data Fetching (React Query & SWR)
What problem do libraries like React Query and SWR solve compared to fetching data with plain useEffect?
BeginnerAnswer
Fetching data with plain useEffect means you have to manually handle loading states, errors, caching, and refetching yourself every single time. React Query and SWR handle all of this automatically, and they also cache results so the same data does not need to be fetched again every time a component appears on the screen.
import { useQuery } from '@tanstack/react-query';
function Products() {
const { data, isLoading, error } = useQuery({
queryKey: ['products'],
queryFn: () => fetch('/api/products').then((res) => res.json()),
});
if (isLoading) return <p>Loading</p>;
if (error) return <p>Something went wrong</p>;
return <ProductList items={data} />;
}Real-world example An online store switches from manually written fetch and useEffect code to React Query, immediately gaining automatic caching so navigating back to a previously visited page shows data instantly instead of showing a loading spinner again.