React Query

React Query

React Query is the library used for caching the API data and fetching...

What is a React Query?

React Query is the library used for caching the API data and fetching, and we use the same Axios or fetch for fetching and hooks for caching, there are more features but for now, we are only considering fetching and caching.

Like, let's understand by an example... So, first, let's understand what the problem react query is solving. In a social media app, there is an API to fetch all the posts, and one to create a post, and as soon as the user creates the post the allPost API should get re-fetched. So, if we are not using react query it won't be able to re-fetch it easily, and that's the problem react query is solving.

There are mainly two hooks,i.e, useQuery and useMutation. It accepts a mandatory key, using which we will re-fetch those.

useQuery hook

useQuery hook is used when we don't need to manipulate the data. It returns many fields and has several options and it gets triggered automatically.

useMutation hook

useMutation hook is used when the data get manipulated. It returns the same fields and options which useQuery has, but the only difference it needs to be called using the mutate().

So, enough of theory, let me show you some code.

useQuery hook implementation

import { Axios } from "axios";
import React from "react";
import { useQuery } from "react-query";

export default function App() {
  const fetchAllPosts = async () => {
    const axios = new Axios();
    return await axios.get(endpoint).then(({ data }) => data);
  };

  const { data, isLoading, isError } = useQuery("allPost", () =>
    fetchAllPosts()
  );

  return <></>;
}

useMutation hook implementation

import { Axios } from "axios";
import React from "react";
import { useMutation } from "react-query";

export default function App() {
  const fetchAllPosts = async (payload) => {
    const axios = new Axios();
    return await axios.post(endpoint, payload).then(({ data }) => data);
  };

  const { mutate, data, isLoading, isError } = useMutation(
    "createPost",
    (payload) => fetchAllPosts(payload)
  );

  return <></>;
}

Now, here comes the main feature of re-fetching those APIs, and there is a hook called invalidateQueries which takes the key, which will trigger the API associated with it. You can place this hook inside the onSuccess of creating a post, like when the user creates the post, the all post API should get re-fetched, so without page relead, the data will get updated.

import React from "react";
import { useQueryClient } from "react-query";

export default function App() {
  const queryClient = useQueryClient();
  queryClient.invalidateQueries("allPost");
  return <></>;
}

Here is the reference to react-query react-query.tanstack.com , there is a lot more, just check their website.