When to Use React Query vs useEffect for Data Fetching

Tommy C
2 min readAug 17, 2023
Photo by Lautaro Andreani on Unsplash

When building React apps, we often need to fetch data from an API.

There are two main ways to do this — with the useEffect hook or with React Query.

But when should you use each one?

In this post, I’ll compare React Query and useEffect for data fetching and give recommendations on when to use each.

The useEffect Hook for Data Fetching

The useEffect hook has been the go-to way to fetch data in React for a long time.

Here’s a quick example:

import { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);

useEffect(() => {
async function fetchData() {
const response = await fetch('/api/data');
const json = await response.json();
setData(json);
}
fetchData();
}, []); // empty dependency array to run once
return <div>{data}</div>;
}

This works well for basic cases. It fetches the data on mount and stores it in the component’s state.

However, useEffect has some downsides:

  • No caching — it refetches on every render
  • No error handling built in
  • Loading and error state need…

--

--

Tommy C

👋 Hi, I'm Tommy. Fitness fanatic, wellness advocate, and your guide to becoming the best you can be. 💪 Let's grow together!