We use a range of tools to help us in our work, and here we share one of our favourites: a solution to handling cached data from an app’s backend API. Let's talk about react-query.
Managing state in apps is a perennial topic for discussion and innovation, especially in the Javascript communities. We have worked with a lot of different solutions over the years at Lola Tech, from stashing objects on the window in early jQuery scripts to experimenting with Zustand and Hookstate. In this post we consider a favorite solution to a common subset of the state-management problem: handling cached data from an app’s backend API.
Since “cache invalidation” is famously one of “The Hard Problems” it should be no surprise that this is an area with many excellent approaches, each with their caveats and tradeoffs. You might choose to combine your server-state cache with your local state store in Redux. Or maybe you will choose Apollo Client because it aligns so well with your GraphQL API. Perhaps you will opt for SWR because you value how it plays with the different page-rendering modes in Next.js. In this post, though, we want to talk about react-query.
In a significant number of the front-end applications we build, especially in high-security spaces like fintech and healthcare, the effective management of server-held state is one of our biggest requirements. React-query addresses this elegantly, with a modern hook-based solution, while remaining agnostic about your underlying API. So long as you can provide a function which can fetch your data from the server or throw an error, you can use react-query. In this it is similar to another favorite, Vercel’s SWR, but with the advantage that react-query plays nicely in React Native as well as web apps.
When we introduce colleagues to react-query for the first time their reactions tend to come in two phases. The first is a mixture of delight - at how little code they need to write - with suspicion - that it will get ugly as soon as things get complex. The second wave happens once they have encountered a tricky situation and found not only that react-query is equal to the task, but that both the library and its excellent documentation were with them all the way. After that the dopamine keeps coming as more sophisticated use-cases keep on demonstrating how elegant and powerful the underlying concepts are.
We can hardly be more complimentary, and if our enthusiasm has stirred your curiosity then we have done our work here. Your next port of call should certainly be https://react-query.tanstack.com where you can spend a little time with well-maintained docs and examples. We will close with enthusiastic thanks and admiration for creator Tanner Linsley and the large and active community behind react-query.