3 min readReact Query · Part 3 of 12

React Query - useIsFetching & useIsMutation

Hey folks, Today it is time to talk about two hooks exposed by react query: useIsFetching and...

#react#reactquery#reacthooks
Luca Del PuppoLuca Del Puppo
Article Series · Part 3 of 12React Query
View full series (12)
  1. #2Previous
    useMutation
  2. #3Reading now
    useIsFetching & useIsMutation
  3. #4Up next
    DevTools
Browse all 12 parts in this series
  1. #1useQuery
  2. #2useMutation
  3. #3useIsFetching & useIsMutationCurrent
  4. #4DevTools
  5. #5Authentication Flow
  6. #6Filter Your Data
  7. #7Enable Query
  8. #8Keys & Prefetching
  9. #9Improve user experience with optimistic update
  10. #10Abort Request
  11. #11Paginated List
  12. #12Infinite Queries

Hey folks,

Today it is time to talk about two hooks exposed by react query: useIsFetching and useIsMutation.

Each of these hooks could be used to understand if there is a fetching request or if there is a mutation request ongoing in the application.

They are useful if we need to create a global loader that appears when there are one or more requests on going.

But how can you use them?

Let’s start with the useIsFetching.

import { useIsFetching } from '@tanstack/react-query';

export default function Loader() {
  const isFetching = useIsFetching();
  if (!isFetching) return null;

  return <>Fetching...</>
}

As you can see, the syntax is pretty simple. You can import the hook from the library and you can use the hook in your components. The hook returns only a boolean value that indicates if there are one or more fetching requests in the application. Then with this data, you can decide if you have to show a loader or not. Easy peasy!

Now it’s time to move to the useIsMutation hook. This hook is similar to the previous one, the only different concept is that this hook handles the mutation requests. Let’s see an example!

import { useIsMutating } from '@tanstack/react-query';

export default function Loader() {
  const isMutating = useIsMutating();
  if (!isMutating) return null;

  return <>Mutating...</>
}

As you can notice, the syntax is the same as the previous one, the only difference stands in the name of the hook and in its concept.

If you want to find more about these two hooks see my Youtube video about them.

ReactQuery - useIsFetching & useIsMutatingClick to play inline · youtube-nocookie.com (no requests until played)
Watch on YouTube

Ok, I think you have an idea of how these two hooks work. I hope you enjoyed this content.

See you soon folks

Bye Bye 👋

p.s. you can find the code of the video in the GitHub repository

Photo by Rahul Mishra on Unsplash

🎬 Watch / View Embedded Resource: https://dev.to/puppo

Luca Del Puppo

Written by Luca Del Puppo

Run, Code & Learn

AI Native Engineer at Nearform based in Povegliano (TV), Italy. Google Developer Expert in Web Technologies, GitKraken Ambassador, and Codemotion Ambassador.