What is react-query?

Essentially, react-query enables/provides a hook-based approach to managing data returned from some kind of server/endpoint/api request (GET, POST, PUT, DELETE). Put simply, it makes it really easy to couple server and client state together. It may seem simple enough but many considerations need to be taken into account depending on an applications specific requirements. Some of the features it offers are listed below.

  • invalidate/refetch data after set time.
  • prefetch page-data.
  • refetch failed/error requests.
  • data polling.
  • can be configured for both rest & graphql

Basic Config

As is common with React (and other component-based development) the react-query library users a "Provider" component to configure.

import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; //v4 update - https://tanstack.com/query/v4/docs/guides/migrating-to-react-query-4#react-query-is-now-tanstackreact-query
// create new queryClient
const queryClient = new QueryClient();
// ...pass to provider
<QueryClientProvider client={queryClient}>
<App />
{/* everything within this component tree will have access react-query */}
</QueryClientProvider>;

Using React-Query

React-query provides a simple to use hooks interface

// current state of queryClient -> useful for pre-updating client, before confirmation of success from server
const queryClient = useQueryClient();
// get data
const {
data: someData,
isLoading,
error,
} = useQuery(
// we can use this key to manage invalidating/refetching server data
["someKindOfKey"], //v4 update - https://tanstack.com/query/v4/docs/guides/migrating-to-react-query-4#react-query-is-now-tanstackreact-query
fetchSomeData
);
// mutation
const {
mutate,
mutateAsync,
isLoading: isLoadingMutation,
error: errorMutation,
} = useMutation(someMutation);