Data is fundamental in any application because it enables dynamic components within a web application. For example, many applications rely on API responses, and how users interact with those responses, such as selecting data or updating data, is possible through state management.
React Query is a library for managing the state of an application. It simplifies tasks such as fetching data from APIs, mutating data, and handling pagination, amongst others.
Let’s go through what React Query is about and how to use it in an application.
What is React Query?
React Query, now known as TanStack Query, is a library used for fetching data and managing server-side state and side effects in React applications. The name was changed to Tanstack Query after it was rebranded to expand beyond React, making it available to other JavaScript frameworks.
It provides an intuitive API for fetching data from RESTful or GraphQL APIs, making it possible to cache results and automatically update data.
TanStack Query provides hooks that manage React state for:
- Data - fetched or cached data
- Loading - indicates a query in progress
- Errors - catches errors from fetching or state mutation
Key Features of React Query
React Query supports features such as;
Pagination and Infinite Scrolling: This involves showing data in smaller sets instead of showing everything at once. It works by dividing data into multiple pages that users can navigate through using controls such as left and right arrows.
It also handles infinite scrolling by fetching the next page while storing data in a cache, allowing users to scroll back to previous pages without having to refetch data.
Query Retries: React Query provides a retry option that instructs the query to retry fetching data again if the request fails, until it succeeds or reaches a set retry limit.
Real-time updates: React Query can automatically refresh data without user action, for example, a reporting dashboard that updates every minute.
Data Fetching and Caching: These are core features of React Query. React Query fetches data from APIs and automatically handles states such as loading, success, and errors.
Once data is fetched, it is stored in a memory cache. This allows retrieval of subsequent requests for the same data it cached, instead of refetching it every time.
Automatic Background Refetching: React Query automatically refetches data to keep it up to date based on events, such as when the user returns to the page.
Mutation handling: This is how React Query manages data modification on the server, e.g., updating or deleting data, ensuring that the UI reflects current data when changes occur.
Query Invalidation: By invalidating specific queries, React Query knows when certain data is outdated. Once invalidated, React Query automatically refreshes the outdated data so the UI reflects the current data or state.
Benefits of React Query
Here are a few benefits of React Query;
Faster Development: React Query reduces boilerplate for tasks such as fetching, error handling, caching, caching validation, and refetching, all handled behind the scenes.
Clear Code: Less boilerplate means more readable and maintainable code, which makes it easier to see and understand how data flows within components.
Data Sharing: Cached data can be shared by multiple components without the need to refetch, and ensures consistency.
Scalability: React Query provides an easy way to manage multiple queries and mutations, keeping the application organized as it grows.
Better Debugging: It provides an easier way to inspect queries, mutations, cache, and states, making debugging more effective.
Managing Data with React Query
In this example, we’ll go through a brief tutorial on how to manage data in React Query.
Prerequisite: To follow along, you should be familiar with setting up a React Project. For this tutorial, we are using VSCode as the development environment.
Step One
Install and Initialize TanStack Query
To install TanStack Query, copy the following command and paste it into your terminal.
npm i @tanstack/react-query
Go to the main.jsx ( or tsx) file, import and initialize the query client from Tanstack, and wrap the App with QueryClient provider as shown in the image above;
Step Two
Fetching Data with useQuery
To query data, you have to use the useQuery hook. useQuery has two objects;
queryKey: is used for refetching and caching data.
queryfn(query function): runs when a query is executed.
In the image shown below, a functional component was created, and its purpose is to fetch data and display it on the screen.
queryKey: Accepts a unique identifier for the query ["jsonData"] queryFn: This is where the fetch function is defined to get data from the API and then convert the response to JSON.
After defining the query, we return an object with data, isLoading, and error. Notice that we are destructuring these states.
The data: This is what we are fetching from the API isLoading State: This is used to tell users that the data is being fetched error: Shows an error message if the request fails
Step Three
Rendering the data
In the return statement, when data is loaded and there are no errors, we loop through the array of posts using data.map, and then create a div with a unique key that displays the title and body of each post.
Note: To see all the properties available from useQuery, press Ctrl + Space (or Cmd + Space on Mac). This will display all the properties you can use with useQuery, including Boolean properties such as isError, fetchStatus, and others.
We also added conditional checks in the component to handle different application states, in this example, isLoading and Error.
isLoading
isLoading is a helper boolean from useQuery that indicates that data is being fetched. While the data is on its way, you can display a message that says it is loading.
Error
Error is also a Boolean property that useQuery provides; it displays an error message if something goes wrong while fetching data.
Step Four
Modify Data with useMutation
useMutation is used when you want to modify data on the server, such as creating, updating, or deleting.
Let's assume we want to add a new post to the server using the useMutation query and the mutationFn (mutation function)
The useMutation query handles the operations that modify the data. In the above image, we see mutatioFn inside the useMutation query.
The mutationFn is where we define what happens when the mutation is triggered. In this case, addNewPost. Inside the mutationFn, we send a post request to the JSONPlaceholder API with the newPost object.
JSON.stringify(newPost) converts the JavaScript object to JSON before it's sent to the server
res.json() converts the server's response to a JavaScript object.
The onSuccess property logs the body of the post to the console after the mutation is successful
The button triggers the mutation, which runs the post request.
React Query simplifies data management compared to useState. For example, when fetching data with useState in React, you have to use a setter function to update the state, and you also need a separate state variable for loading and error.
React Query also provides data, isLoading, and other utilities such as refetch, which help reduce boilerplate code and keep code cleaner and maintainable.
Summary
React Query is a powerful tool for fetching and managing server-side data in React applications. Its core concept, the useQuery hook, simplifies the process of fetching data and automatically handles states like loading and error behind the scenes, reducing the amount of code developers need to write.
It also keeps data consistent across components, supports managing multiple queries and mutations in large applications in an organized manner, which promotes scalability, and provides background refetching to improve user experience, amongst other features.
To learn more about what React Query is capable of, visit the official website for detailed documentation.
Frequently Asked Questions
Can I use JavaScript frameworks like React or Vue.js in my WordPress plugin?
Yes, you can. Enqueue your scripts properly using wp_enqueue_script(). Ensure compatibility with WordPress core and consider using the REST API for seamless communication.
Are there specific hosting requirements for JavaScript frameworks like React, Angular, or Vue.js?
Answer: Generally, hosting for client-side JavaScript frameworks like React, Angular, or Vue.js does not require specialized servers since the frameworks run in the user's browser.
Is Next.js only for React developers and Nuxt.js only for Vue developers?
While Next.js is primarily associated with React, and Nuxt.js is built on Vue.js, you are not limited to using them exclusively with their respective libraries. Both frameworks can be used to build applications in their native library (Next.js with React, Nuxt.js with Vue.js), but they also offer flexibility for mixing and matching with other technologies if needed. For instance, you can use Vue components within a Next.js project or React components within a Nuxt.js project.
Can I migrate an existing React or Vue project to Next.js or Nuxt.js?
Yes, it is possible to migrate an existing React or Vue project to Next.js or Nuxt.js. However, the migration process may involve adjustments to the project structure, routing, and codebase to align with the conventions of the chosen framework. It is recommended to consult the migration guides provided by Next.js and Nuxt.js for detailed instructions.
Jessica Agorye is a developer based in Lagos, Nigeria. A witty creative with a love for life, she is dedicated to sharing insights and inspiring others through her writing. With over 5 years of writing experience, she believes that content is king.
View all posts by Jessica Agorye