How to Implement React Query in Your Next Web Development Project: A Comprehensive Guide

React Query Banner

How to Implement @tanstack/react-query in Your Next Web Development Project: A Comprehensive Guide

Web development can be an arduous task with plenty of challenges to overcome. However, with the creation of libraries like react and @tanstack/react-query, developers now have a much easier time when it comes to handling state management and fetching data from APIs.

React Query is a powerful library that simplifies fetching, caching, synchronizing and updating server state in your applications. It offers performant and efficient data fetching for the React community and is widely adopted. In this guide, we'll take a detailed look at how you can implement @tanstack/react-query in your next web development project.

Prerequisites

Before getting started with @tanstack/react-query, make sure that your project is based on React. You can create a new React application by running npx create-react-app application-name on your terminal, presuming that you have the NodeJs ecosystem installed on your machine.

Installation

To install @tanstack/react-query, simply run npm i react-query. Once this is done, you need to import it into your project files before trying to use it.

import React, { useState } from "react";
import ReactDOM from "react-dom";
import {
  QueryClient,
  QueryClientProvider,
  useQuery,
} from "@tanstack/react-query";

Features of @tanstack/react-query

@tanstack/react-query boasts of some unique features which include, but are not limited to;

  • Incredible caching capabilities
  • Concurrent background updates
  • Real-time query sharing
  • Suspense mode
  • Pagination and infinite loading

To know more about these features and how they work, visit the official documentation of react-query

Usage

Data fetching with QueryClient and useQuery

Using QueryClient directly allows you to manage your queries inside the component that requires it.

import React, { useMemo } from 'react'
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query/devtools'

const queryClient = new QueryClient()

export default function App() {
  return ()
}

function Todos() {
  const { isLoading, data, error } = useQuery('todos', () => fetch('https://jsonplaceholder.typicode.com/todos').then((res) => res.json()))

  if (isLoading) return 'Loading...'

  if (error) return 'An error has occurred: ' + error.message

  return (
    {
      data.map((todo) => (
      {todo.title}
      ))
    }
  )
}

Invalidation Query

To cache your query, you'll want to set an id for your query, like so:

const getTodos = async () => {
  const res = await fetch(`/api/todos`);
  return res.json();
};
getTodos.queryKey = "todos"; // Set a consistent id for this query

// In Components.js

const { data } = useQuery(getTodos.queryKey, getTodos);
console.log(data);

Mutation Example

In the following example, we show an implementation of useMutation, by calling an email signup form submission API endpoint:

import React, { useState } from 'react'
import ReactDOM from 'react-dom'
import { useMutation } from '@tanstack/react-query'

function SignUpForm() {
  const [formData, setFormData] = useState({
  email: '',
  password: '',
  confirmPassword: '',
})

const [signUp, { status, data, error }] = useMutation(signUpUser)

function handleSubmit(e) {
  e.preventDefault()
  signUp(formData)
}

return (
    Sign Up Form
    {status === 'success' ? (Success - {JSON.stringify(data)}
    ) : (
      <input
        type="email"
        placeholder="email"
        onChange={(event) =>
        setFormData({ ...formData, email: event.target.value })
        }
      />

      <input
        type="password"
        placeholder="Password"
        onChange={(event) =>
        setFormData({ ...formData, password: event.target.value })
        }
      />


      <input
        type="password"
        placeholder="Confirm Password"
        onChange={(event) =>
        setFormData({
        ...formData,
        confirmPassword: event.target.value,
        })
        }
      />
      <button>
        Sign Up
      </button>
    )}
    {status === 'loading' &&
    Loading...
    }
    {status === 'error' && (
        {error.message}
      )
    }
  )
}

// Mock API Call Function
const signUpUser = async ({ email, password }) => {
const response = await fetch('/api/signup', {
  method: 'POST',
  body: JSON.stringify({ email, password }),
})

if (!response.ok) {
  throw new Error('Network response was not ok');
}
return response.json();
};

ReactQueryDevtools

How do you view previously cached data? React Query maintains an object that holds information on all the different queries made after it was initialized. React query also provides a helpful devTool for viewing all mutations and queries made in your application. To use this devTool, simply import it into your project and add it to your component.

import React from "react";
import ReactDOM from "react-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

import App from "./App";

const queryClient = new QueryClient();

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById("root")
);

Conclusion

As we have seen in this comprehensive guide, implementing @tanstack/react-query in your project not only simplifies state management but also makes it easier to handle network requests with minimal configuration. With its great features such as caching capabilities and concurrent background updates, achieving a smooth workflow while developing and testing your applications just got easier. So why not give it a try in your next web development project”.

References