Home Web Front-end JS Tutorial Stop using useQuery from React-Query !

Stop using useQuery from React-Query !

Aug 06, 2024 am 05:25 AM

Stop using useQuery from React-Query !

In any web application, managing loading and error states is crucial. Displaying loading states keeps the user informed, but historically, this management can be tedious to implement manually.

React Query greatly simplifies the handling of loading states and global states. Indeed, React Query avoids redundant requests, thereby optimizing the application's performance.

Let's take a code example that implements a loading state in our application.

Define a hook to fetch a list of users:

export const useUsers = () => {
  const { data, isLoading } = useQuery<User[]>({
    queryKey: ["users"],
    queryFn: async () => {
      const response = await fetch("https://jsonplaceholder.typicode.com/users");
      await new Promise((resolve) => setTimeout(resolve, 2000));
      return response.json();
    },
  });

  return {
    users: data?.slice(0, 4) || [],
    isLoading,
  };
};
Copy after login

Here, we fetch four users with useQuery. We add a 2-second delay to illustrate the loading state. We then return the data and a boolean for the loading state.

On the component side, let's create a component named Example:

const Example = (): JSX.Element => {
  const { users, isLoading } = useUsers();

  if (isLoading) {
    return <div>Loading...</div>;
  }

  return (
    <div className="container">
      <div className="user-action">
        <h1>Users</h1>
        <div>
          <button>Add users</button>
        </div>
      </div>
      <UsersList users={users} />
    </div>
  );
};
Copy after login

In this component, we use our hook to fetch the list of users. Before rendering the view, we perform an "early return" with a loading message, then display the title, button, and users.

Limitations and Alternatives

However, each network call requires explicit management of the loading state. If the code is not factorized, some elements of the view might be waiting to be displayed, such as the title and action.

Here is an alternative to avoid blocking the view:

import "./App.css";
import UsersList from "./UsersList";
import { useUsers } from "./useUsers";

const Example = (): JSX.Element => {
  const { users, isLoading } = useUsers();

  return (
    <div className="container">
      <div className="user-action">
        <h1>Users</h1>
        <div>
          <button>Add users</button>
        </div>
      </div>
      {isLoading ? <div>Loading...</div> : <UsersList users={users} />}
    </div>
  );
};
Copy after login

Here, we use conditional rendering instead of an "early return". This solution is less readable and harder to maintain in complex components.

The Ideal Solution: A Generic Loading Component

The most ingenious solution is to create a component that renders our loading message or our main component based on a variable.

type Props = PropsWithChildren<{
  isLoading: boolean;
}>;

const LoadingWrapper = ({ children, isLoading }: Props): JSX.Element => {
  if (isLoading) {
    return <div>Loading...</div>;
  }

  return <>{children}</>;
};
Copy after login

Usage in Our Component

const Example = (): JSX.Element => {
  const { users, isLoading } = useUsers();

  return (
    <div className="container">
      ...
      <LoadingWrapper isLoading={isLoading}>
        <UsersList users={users} />
      </LoadingWrapper>
    </div>
  );
};
Copy after login

This factorization centralizes the conditional rendering logic and unifies the use of loading messages, offering cleaner and more maintainable code.

Discover the Magic of Suspense

But now, if I tell you that this component we just created is already built into React. Even better, it's magical! No more manual management of isLoading states!

How?

With React's Suspense (React version >= 16.6), everything becomes simpler and cleaner. Suspense allows you to explicitly declare to React that a component is waiting for asynchronous data, and React takes care of managing everything for us.

Implementing useSuspenseQuery

Let's use useSuspenseQuery to automatically manage the loading state. Here's how to do it:

Hook to Fetch Users

export const useUsersSuspense = () => {
  const { data } = useSuspenseQuery<User[]>(
    ...
  );

  return {
    users: data?.slice(0, 4) || [],
    // Without the isLoading
  };
};
Copy after login

Usage in the Component with Suspense

Now, let's update our Example component to use Suspense:

const UsersComponent = (): JSX.Element => {
  const { users } = useUsersSuspense();

  return <UsersList users={users} />;
};

const Example = (): JSX.Element => {
  return (
    <div className="container">
      <div className="user-action">
        <h1>Users</h1>
        <div>
          <button>Add users</button>
        </div>
      </div>
      <Suspense fallback={<div>Loading...</div>}>
        <UsersComponent />
      </Suspense>
    </div>
  );
};
Copy after login

Advantages of Suspense

With Suspense, we centralize the management of the loading state in one place, making the code more readable and maintainable. The Suspense fallback automatically displays as long as the data is not available, eliminating the need to manually manage isLoading states.

Moreover, Suspense encourages development teams to factorize their code. By using standardized loading components and asynchronous state handlers, developers can create reusable and consistent modules, thus improving code quality and maintainability in the long term.

Conclusion

Using Suspense and useSuspenseQuery revolutionizes the management of loading states in React applications. This approach not only simplifies the code but also enhances the user experience by ensuring smooth and consistent rendering. Transitioning from useQuery to useSuspenseQuery is a natural evolution for cleaner and more efficient applications.

Additionally, integrating Suspense encourages development teams to factorize their code. In conclusion, adopting Suspense and useSuspenseQuery is not just a technical improvement, but also a step towards healthier and more effective development practices.

My Newsletter :D

The above is the detailed content of Stop using useQuery from React-Query !. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles