新鲜 / 健康 / 便利 / 快速 / 放心
In a nutshell, React Query helps fetch and cache server-side data and share it across the components. It gives us two main hooks for data fetching: useQuery and useMutation. We can use useQuery to fetch data from the network and cache it.
In this article, we will see how useQuery can ease our job in polling and refetching APIs conditionally with a small example. We will now dive into the requirements without further ado.
React Query checklist for polling
The simplified rough outline of UI can be seen in the image below:
The demo source code is available here.
We can extract this to a custom hook (not battle-tested) as seen below.
This hook satisfies our requirements. However there are a few things that we might need in real-time that might require additional work.
If we convince ourselves to use React Query, then all these operations become even more simpler with a few lines of useQuery: it’s highly configurable with a lot of batteries included. If the reduced lines of code do not interest you, then do have a look at the pros listed later in the blog.
Our custom hook now will just have few lines, as shown below:
We can cache data at a configurable time interval and also auto fetch it. If the data retrieval is successful, then it will update the UI or it will silently fail. We can eliminate the need to maintain the same reference or perform deep equal comparisons.
Now if we need to read the data in any other component, we can do so just by calling queryClient.getQueryData(…). Automatically when the component unmounts, all the listeners will be unsubscribed by React Query. No additional work is required.
Earlier, we were using redux store to place the server data that is shared across multiple components. By using React Query, we don’t need to do that any more, and it also reduces the need for a lot of boilerplate code. We highly recommend that you test and play around with React Query’s useQuery hook to see the benefits for yourself.
Till then, keep an eye out for more posts from us on all things code!