DEV Community

Cover image for 🔥 What's new update in React Query 5.0 🤯
TAQUI ⭐
TAQUI ⭐

Posted on

🔥 What's new update in React Query 5.0 🤯

What's New in The New React Query 5.0

React Query has become an essential library for many developers working on React applications. With every new version, it brings exciting features and improvements that simplify data fetching and state management. React Query 5.0 is no exception. In this blog post, we'll explore the latest features and improvements in React Query 5.0 with practical examples.

✅Checkout Official documentation

And Don't Forget to 👇:

Follow me in Github

Installation

Before we dive into the new features, make sure you have React Query 5.0 installed in your project. You can do this by running:

npm install react-query@5
Enter fullscreen mode Exit fullscreen mode

Now, let's take a closer look at the new features.

1. Suspense Integration

React Query 5.0 introduces full suspense mode support. This means that you can use React Suspense to handle loading states and display fallback UI while data is being fetched. This integration simplifies asynchronous rendering, making your code more concise and easier to reason about.

Here's an example of using suspense with React Query 5.0:

import { useQuery } from 'react-query';

function UserProfile({ userId }) {
  const { data, error } = useQuery(['user', userId], fetchUser);

  if (error) {
    throw error; // Handle errors with Suspense
  }

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.email}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

2. React Query Devtools

React Query 5.0 comes with a new and improved Devtools extension. This tool allows you to inspect your queries, mutations, and caches right in your browser's developer tools. It provides a visual representation of your data fetching and state management, making it easier to debug and optimize your application.

React Query Devtools

3. TypeScript Support

TypeScript users will be pleased to know that React Query 5.0 now ships with first-class TypeScript support. This means better autocompletion and type inference, making your codebase more reliable and less error-prone.

import { useQuery } from 'react-query';

interface User {
  id: number;
  name: string;
  email: string;
}

function UserProfile({ userId }: { userId: number }) {
  const { data, error } = useQuery<User>(['user', userId], fetchUser);

  // TypeScript will ensure 'data' has the correct shape
  // and that 'userId' is a number.

  if (error) {
    throw error; // Handle errors with Suspense
  }

  return (
    <div>
      <h1>{data.name}</h1>
      <p>{data.email}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

4. Improved Mutations

React Query 5.0 brings improvements to mutations, allowing you to easily update your local cache after a mutation. The onMutate and onSuccess options provide greater control over how your UI updates when a mutation succeeds.

import { useMutation, useQueryClient } from 'react-query';

function App() {
  const queryClient = useQueryClient();

  const { mutate } = useMutation(updateTodo, {
    onMutate: (newTodo) => {
      // Optimistically update the local cache
      queryClient.setQueryData(['todo', newTodo.id], newTodo);
    },
    onSuccess: () => {
      queryClient.invalidateQueries('todos');
    },
  });

  // ...
}
Enter fullscreen mode Exit fullscreen mode

5. New isPending Property in useMutation with Example 🔥

The isPending property in useMutation is a fantastic addition to React Query 5.0. It allows you to easily track the pending state of your mutations, making it simpler to show loading indicators or disable UI elements during mutation execution. Let's create an awesome example to demonstrate how to use isPending in a real-world scenario.

Scenario: Updating a To-Do Item

Imagine you have a to-do list application, and you want to update the title of a to-do item. You want to display a loading spinner while the update is in progress. Here's how you can do it using the isPending property in useMutation.

import React, { useState } from 'react';
import { useMutation, useQueryClient } from 'react-query';

function TodoItem({ todo }) {
  const queryClient = useQueryClient();
  const [newTitle, setNewTitle] = useState(todo.title);

  const updateTodoMutation = useMutation(
    (newTitle) => updateTodoItem(todo.id, newTitle),
    {
      // Optimistically update the local cache
      onMutate: (newTitle) => {
        queryClient.setQueryData(['todo', todo.id], {
          ...todo,
          title: newTitle,
        });
      },
      // Invalidate the cache after a successful mutation
      onSuccess: () => {
        queryClient.invalidateQueries(['todo', todo.id]);
      },
    }
  );

  const handleTitleChange = (e) => {
    setNewTitle(e.target.value);
  };

  const handleUpdateTodo = () => {
    updateTodoMutation.mutate(newTitle);
  };

  return (
    <div>
      <input
        type="text"
        value={newTitle}
        onChange={handleTitleChange}
        disabled={updateTodoMutation.isPending}
      />
      <button onClick={handleUpdateTodo} disabled={updateTodoMutation.isPending}>
        {updateTodoMutation.isPending ? 'Updating...' : 'Update Todo'}
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, we have a TodoItem component that allows the user to update the title of a to-do item. We use useMutation to handle the update. The updateTodoMutation object has an isPending property that we use to disable the input field and show a loading message on the button while the mutation is in progress.

The onMutate callback is used for optimistic updates, where we immediately update the local cache with the new title, providing a smooth user experience.

This example demonstrates how the isPending property in useMutation simplifies handling loading states during mutations, providing a better user experience in your application.

6. React Query Server Components

In response to the growing popularity of Server Components, React Query 5.0 introduces server components support. You can now use React Query seamlessly in server-rendered applications, enabling data prefetching and caching on the server side.

Conclusion

React Query 5.0 brings some exciting features and improvements, making data fetching and state management in your React applications even more straightforward. With suspense integration, the new Devtools extension, TypeScript support, improved mutations, and server component compatibility, React Query continues to be a valuable tool for modern web development.

To learn more about React Query 5.0 and explore its documentation, visit the official website. Upgrade your projects to take advantage of these new features and enhance your development experience.

Written by Md Taqui Imam

Happy coding!

Top comments (0)