A beginners guide to React-query (Tanstack query v5)
A while ago I wrote a series on react-query. Now, I’m deciding to put together another one because, as with all things in tech, a lot has changed. In this new series, I would do my best to guide an absolute beginner through the amazing tool from novice to a point where you’re hopefully comfortable working with react-query. I will provide insights into its core principles, practical use cases, and essential components.
In the world of front-end development, managing asynchronous data fetching, caching, and synchronization can often be a challenging task. React Query emerges as a powerful tool to streamline these processes, making data management in React applications more efficient and intuitive.
React Query is a library that simplifies data fetching and management in React applications. It offers a declarative approach to handle asynchronous operations, such as fetching data from APIs, caching responses, and managing loading states, all in a clean and efficient manner. Unlike traditional state management libraries, React Query focuses on managing asynchronous server-side data, providing a specialized solution for this specific aspect of application development. It is not a replacement for global store libraries like Zustand or Redux-toolkit, as it aims to handle state on the server-side.
Personally, react-query is my go-to tool for API integrations whenever I start a project, when you think about it, what’s not to love?
It comes with built-in features that make for a simplified and easy-to-manage means to integrate APIs on the frontend.
- Declarative Data Fetching: React Query allows developers to fetch data declaratively using hooks like
useQuery
. By abstracting away the complexities of imperative data fetching, developers can focus on building user interfaces while React Query handles data management under the hood. - Automatic Caching: One of the standout features of React Query is its built-in caching mechanism. It caches query results by default, ensuring that subsequent requests for the same data are served from the cache rather than making redundant network calls. This improves the performance and responsiveness of applications, especially in scenarios where data doesn’t frequently change.
- Automatic Background Data Refetching: React Query provides automatic background data refetching, ensuring that cached data remains fresh. We can configure data refetching intervals or trigger refetching based on specific conditions, guaranteeing that users always have access to the latest data without sacrificing performance.
- Error Handling and Retry Strategies: React Query simplifies error handling by providing built-in mechanisms to handle errors gracefully. This allows us to define custom error handling logic and retry strategies which allow applications to recover from network failures or server errors seamlessly.
Key Components of React query
QueryClientProvider — the top-level component wraps our React application, providing our application with a global context of the query client instance. It ensures that query-related functionality is available throughout the component tree.
import { QueryClientProvider } from 'react-query';
function App() {
return (
<QueryClientProvider>
{/* Your application components */}
</QueryClientProvider>
);
}
The QueryClientProvider
receives a required client prop which is the QueryClient
instance.
QueryClient — is the central hub for managing queries, caching data, and handling background data refetching. It serves as a global singleton instance that can be configured with various options to tailor its behavior according to your application’s needs.
const queryClient = new QueryClient();
The query client can be configured with certain options that help us specify how it should behave within our application.
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
staleTime: 30000,
refetchOnWindowFocus: false,
},
},
});
While react query offers a long list of options, in my experience the three in the snippet above are usually the most used.
retry
— specifies the number of attempts we want react query to make before it gets a response from a query.
staleTime
— time in milliseconds before considering data stale and attempting to get fresh data.
refetchOnWindowFocus
— disables automatic refetching on window focus. By default this is true.
Putting these together, our root App component would look like this
import { QueryClientProvider, QueryClient } from 'react-query';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 1,
staleTime: 30000,
refetchOnWindowFocus: false,
},
},
});
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* Your application components */}
</QueryClientProvider>
);
}
Let’s talk about the two core concepts of react-query.
Mutations and Queries. These would be discussed in further detail in future parts of the series, but for now, an overview.
Mutations are typically used to create/update/delete data or perform server side-effects. They are implemented via the useMutation
hook and can only be in one of the following states at any given moment: isIdle
isPending
isError
isSuccess
. For clarity; isIdle
is the state of a mutation when it is currently idle or in a fresh/reset state while isPending
is the state of a currently running mutation. isError
and isSuccess
simply tell if the mutation failed of returned a success status.
Queries are used with any Promise based method (including GET and POST methods) to fetch data from a server. Just like mutations, queries
have states; isPending
isError
isSuccess
there is also and isFetching
state that is true anytime the query is fetching data — even in the background.
It is recommended to use mutations
when we need to modify data on the server.
If you’re excited to get your hands dirty with react-query you go ahead to install and set it up in your react application.
npm i @tanstack/react-query
pnpm add @tanstack/react-query
yarn add @tanstack/react-query
bun add @tanstack/react-query
By understanding the key components and principles behind React Query, we can streamline data management in our applications and deliver better user experiences. Whether fetching data from APIs, handling real-time updates, or implementing complex data synchronization logic, React Query empowers developers to tackle data-related challenges with ease.