Harnessing the Power of Tanstack Query: useQuery and useMutation

Atharva MulgundAtharva Mulgund
3 min read

Tanstack Query (previously known as React Query) is a powerful data-fetching library that simplifies data synchronization in React applications. In this article, we will delve into two of its essential hooks: useQuery and useMutation. These hooks enable efficient data fetching, caching, synchronization, and more.

What is Tanstack Query?

Tanstack Query provides hooks for fetching, caching, synchronizing, and updating server state in your React applications without the need to manage complex state logic manually. It offers a robust solution for handling asynchronous operations in a declarative manner.

useQuery: Fetching Data Made Easy

The useQuery hook is designed for fetching and caching data. It allows you to declaratively fetch data from an API and handles the caching and updating of data seamlessly.
Here's a basic example of how to use useQuery to fetch data from an API:

import React from 'react';
import { useQuery } from '@tanstack/react-query';
import axios from 'axios';

const fetchTodos = async () => {
  const { data } = await axios.get('https://jsonplaceholder.typicode.com/todos');
  return data;
};

const Todos = () => {
  const { data, error, isLoading } = useQuery({ queryKey: ['todos'], queryFn: fetchTodos });

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

  return (
    <div>
      <h1>Todos</h1>
      <ul>
        {data.map(todo => (
          <li key={todo.id}>{todo.title}</li>
        ))}
      </ul>
    </div>
  );
};

export default Todos;

Explanation

  1. Define a fetch function: The fetchTodos function uses axios to fetch data from an API.

  2. Use useQuery: The useQuery hook takes an object with queryKey and queryFn properties. queryKey ensures unique identification for the query, and queryFn is the function to fetch the data.

  3. Handle different states: The hook returns an object with data, error, and isLoading. You can use these to handle loading states, errors, and to display the fetched data.

useMutation: Simplifying Data Mutations

While useQuery is for fetching data, useMutation is used for creating, updating, or deleting data. It provides a way to perform side effects and integrates seamlessly with Tanstack Query's cache.
Here's an example of how to use useMutation to create a new todo item:

import React from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import axios from 'axios';

const addTodo = async (newTodo) => {
  const { data } = await axios.post('https://jsonplaceholder.typicode.com/todos', newTodo);
  return data;
};

const AddTodo = () => {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: addTodo,
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });

  const handleAddTodo = () => {
    mutation.mutate({ title: 'New Todo', completed: false });
  };

  return (
    <div>
      <button onClick={handleAddTodo}>Add Todo</button>
    </div>
  );
};

export default AddTodo;

Explanation

  1. Define a mutation function: The addTodo function uses axios to post a new todo item.

  2. Use useMutation: The useMutation hook takes an object with mutationFn and an onSuccess callback.

  3. Handle success: The onSuccess callback invalidates the ['todos'] query to ensure the list is refetched with the new data.

  4. Trigger the mutation: Call mutation.mutate with the new todo item when the button is clicked.

Conclusion

Tanstack Query's useQuery and useMutation hooks provide a robust and declarative approach to data fetching and mutations in React applications. They help manage server state efficiently, allowing developers to focus on building rich, interactive UIs without worrying about the complexities of data synchronization.

By leveraging these hooks, you can ensure that your application remains responsive, reliable, and maintainable. Happy coding!

1
Subscribe to my newsletter

Read articles from Atharva Mulgund directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Atharva Mulgund
Atharva Mulgund

Software Developer| Passionate about MERN | React.js | Angular | Javascript | Typescript