DEV Community

padmajothi Athimoolam
padmajothi Athimoolam

Posted on

Simplifying Fetching Data with React Query: Replacing useEffect

React Query

React Query's core functionality revolves around fetching and caching data from an API and handling state management, while search engines like Google allow us to query and retrieve relevant information from an extensive database. In this blog, we'll explore how React Query can replace useEffect for data fetching, leading to cleaner and more maintainable code.

Understanding React Query

React Query is a data-fetching library that simplifies the process of managing server state in React applications. It provides hooks for fetching, caching, and syncing server data without the complexity that often comes with useEffect.

Why Replace useEffect?

While useEffect is useful for managing side effects like data fetching, it can lead to complicated code structures. You often find yourself writing multiple effects for different data dependencies, handling loading states, and managing cleanup functions. This can quickly become messy

Benefits of Using React Query

Simplified Data Fetching: React Query abstracts away the complexities of data fetching and state management.

Automatic Caching: It automatically caches fetched data, reducing unnecessary requests.

Background Updates: Data can be kept fresh in the background, ensuring users see the most up-to-date information.

Built-in Loading and Error States: React Query provides loading and error states out of the box, making UI management easier.

Replacing useEffect with React Query

Let’s consider an example where we fetch user data from an API. Here’s how you might traditionally use useEffect:

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

const UserProfile = () => {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/user');
        if (!response.ok) throw new Error('Network response was not ok');
        const data = await response.json();
        setUser(data);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

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

  return <div>{user.name}</div>;
};
Enter fullscreen mode Exit fullscreen mode

Now, let’s see how we can refactor this code using React Query:

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

const fetchUser = async () => {
  const response = await fetch('https://api.example.com/user');
  if (!response.ok) throw new Error('Network response was not ok');
  return response.json();
};

const UserProfile = () => {
  const { data: user, isLoading, isError, error } = useQuery('user', fetchUser);

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

  return <div>{user.name}</div>;
};
Enter fullscreen mode Exit fullscreen mode

useQuery Hook: This hook replaces useEffect for data fetching. It accepts a unique key (in this case, 'user') and a function to fetch the data.

Loading and Error Handling: Instead of managing loading and error states manually, React Query provides isLoading, isError, and error directly from the useQuery response.

_Cleaner Code: _The resulting code is simpler and easier to read. You don’t have to worry about cleanup or dependency arrays.

Conclusion

React Query significantly streamlines the process of managing server state in React applications. By replacing useEffect with React Query’s powerful hooks, you can simplify your code, improve readability, and enhance user experience. If you haven’t yet tried React Query, now is a great time to start exploring its capabilities!

Top comments (0)