When to Use React Query or useEffect for Data Fetching
Tags: webdev, react
Published: 2024-02-25 11:43:26

When it comes to data fetching in React Applications all developers often face a dilemma what should we use to React Query or traditional useEffect hooks?

Two commonly used tools for these purposes are React Query and useEffect. But both approaches have their own strengths and weaknesses.

In this blog, we will explore how and when two approaches are used and why.

**Using React Query for Data Fetching**

React Query is a powerful library designed specifically for fetching, caching, synchronizing, and updating server state in React applications. It offers a declarative API and integrates seamlessly with React components.

**Key Features:**

1. Declarative Data Fetching:** React Query provides a declarative approach to data fetching, making it easy to fetch and manage data in React components.

**2. Caching:** It automatically caches fetched data, optimizing performance by reducing unnecessary network requests.

**3. Automatic Data Refetching:** React Query can automatically refetch data based on various triggers such as stale time, window focus, or specific actions.

**4. Mutation Management:** It simplifies managing mutations (e.g., POST, PUT, DELETE requests) and provides built-in support for optimistic updates and error handling.

**Example:**

```
import { useQuery } from 'react-query';

async function fetchUsers() {
  const response = await fetch('/anik/v1/data');
  if (!response.ok) {
    throw new Error('Network response was not ok');
  }
  return response.json();
}

function UsersList() {
  const { isLoading, error, data } = useQuery('users', fetchUsers);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UsersList;

```

**Using useEffect for Data Fetching**

useEffect is a built-in React hook used for handling side effects in functional components. It allows you to perform operations such as data fetching, subscriptions, or DOM manipulations after component renders.

**Key Features:**

**1. Lifecycle Management:** useEffect provides a way to perform 2 side effects in functional components similar to lifecycle methods in class components.

**2. Dependency Tracking:** It enables you to specify dependencies, ensuring that the effect runs only when certain values change.

**3. Cleanup:** You can return a cleanup function from useEffect, which executes when the component unmounts or before the effect runs again.

**4. Custom Hooks:** useEffect can be used to create custom hooks for encapsulating logic and reusing it across components.

**Example Code:**

```
import React, { useState, useEffect } from 'react';

function UsersList() {
  const [users, setUsers] = useState([]);

  useEffect(() => {
    const fetchUsers = async () => {
      try {
        const response = await fetch('/anik/v1/data');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const data = await response.json();
        setUsers(data);
      } catch (error) {
        console.error('Error fetching users:', error);
        // You can handle errors here, e.g., set an error state
      }
    };

    fetchUsers();
  }, []); // Empty dependency array ensures the effect runs only once

  return (
    <ul>
      {users.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default UsersList;

```
**Conclusion:**

Both React Query and useEffect serve distinct purposes in React development. React Query is ideal for managing complex data fetching scenarios with built-in caching and mutation management, while useEffect is suitable for basic data fetching and other side effects within functional components. Understanding the strengths and use cases of each tool empowers developers to make informed decisions when architecting React applications.