React › Data Fetching (React Query & SWR)
Why is it usually better to use a data fetching library instead of writing your own fetch logic in every component?
BeginnerAnswer
Writing your own fetch logic in every component means repeating the same loading, error, and caching code over and over, and it is easy to make small mistakes, like forgetting to cancel a request when a component unmounts. A dedicated library like React Query or SWR handles all of these details consistently, tested by thousands of other developers, saving time and reducing bugs.
// Repeated manually in every component, error prone
useEffect(() => {
let cancelled = false;
fetch(url).then((res) => res.json()).then((data) => {
if (!cancelled) setData(data);
});
return () => { cancelled = true; };
}, [url]);
// Handled automatically by a library
const { data } = useQuery({ queryKey: [url], queryFn: () => fetch(url).then((res) => res.json()) });Real-world example A growing team notices they had written slightly different, occasionally buggy fetch logic in over a dozen different components, and standardizes on React Query to fix the inconsistencies and reduce duplicated code.