Welcome to the new week! Tomasz Ducin is back with us to explain the next parts of Frontend Architecture - this time with a deeper, more hands-on walkthrough of Frontend State Management on the React Query example. And this is a free episode available to all, so check it out! Why did we decide to zoom in on React Query? It’s a novel approach that can simplify front-end and back-end communication. We wanted to show a practical example of a dedicated technology for handling server data, especially given how often I see teams mix local UI state and remote data in ways that cause stale info, redundant fetching, and scattered “loading” flags. Tomek walked me through exactly why React Query solves those problems. And Tomek is one of the best people I know, specialising in Frontend and Architecture. He’s an Independent Consultant, Architect, Developer, Speaker, and Trainer. Expertise in Web Technologies & Software Architecture. Angular Devtools Contributor. Egghead Instructor. Just check the video to see how he used visuals to explain React Query and state management work. What else have we discussed? Tomek emphasized the crucial distinction between purely local UI data, such as toggles or form inputs, and data you fetch from a server. When these two categories are combined in one place, it becomes unclear which part of your code is responsible for updates, which can result in inconsistent behaviour. Keeping them separate helps maintain a clean structure and ensures each data part is updated in the right context. Tomek then outlined the main challenges: * caching strategies, * time-to-live settings, * stale-while-revalidate patterns. He also discussed query keys, which let you organize and invalidate server responses based on what actually changed - no brute-force reloading. We jumped into real code, showing how React Query handles data fetching and background prefetches and automatically updates the UI when tabs come in and out of focus. Tomek demonstrated how to set mutation hooks for things like deleting a record and how easy it is to invalidate just the relevant pieces of the cache. The DevTools panel gave a clear view of each query’s status, simplifying debugging. Tomek also showed us and proved that even though technology started in the React community, it can be used in other frameworks like Angular. Actually, it’s not called a React Query anymore, but Tanstack Query. What surprised me was the overlap with backend patterns, like pub/sub or connection pooling. Tomek’s explanation showed that when React Query decides whether to serve cached data or make a new HTTP call, it’s basically doing a form of “pooling” and “subscription” management. That’s a familiar concept in many server-side architectures, which shows how these patterns aren’t just front-end tricks. Logically, it’s not far from what we discussed in Mastering Database Connection Pooling. So again, that showed that we should not put a fence between us and discuss whether we face Frontend or Backend Architecture, it’s just Architecture! I learned a lot, and I’m sure that you’ll learn to. Check the video, comment, and tell us how you liked it. Please also send us the topic that you’d like us to discuss next time. Tomek has a lot of fuel in his back! Check also more from Tomek: * Blog * LinkedIn Profile, * Bluesky Profile, * Egghead courses, * His Polish course Architecture on Frontend (yes, it’s polished!) Of course, React Query documentation. And other webinars! Cheers! Oskar * #1 - From CRUD to Event Sourcing * #2 - Keep your streams short! Or how to model Event-Sourced systems efficiently * #3 - Implementing Distributed Processes * #4 - From CRUD to CQRS in Practice * #5 - Architecture Weekly 100 Edition - Live Q&A * #6 - Alexey Zimarev - You don't need an Event Sourcing framework. Or do you? * #7 - Design and test Event-Driven projections and read models * #8 - Slim down your aggregates! * #9 - Radek Maziarka - Modularization with Event Storming Process Level * #10 - PostgreSQL Superpowers in Practice * #11 - Maciej "MJ" Jędrzejewski - Evolutionary Architecture: The What. The Why. The How. * #12 - Jeremy D. Miller: Simplify your architecture with Wolverine * #13 - Yves Goeleven - The Fantastic 9 * #14 - Mateusz Jendza - Why Verified Credentials is the Future of Digital Identity! * #15 - Mário Bittencourt: Leveraging BPMN for Seamless Team Collaboration in Software Development * #16 - Papers We Love #1 - Sagas (Hector Garcia-Molina, Kenneth Salem) * #17 - Simple patterns for events schema versioning * #18 - Andrea Magnorsky: Introducing Bytesize Architecture Sessions! * #19 - Laïla Bougriâ: Debug your thinking * #20 - Papers We Love #2 - How do committees invent? (Melvin E. Conway) * #21 - Michael Drogalis: Building the product on your own terms * #22 - On Performance Testing with Jarosław Pałka * #23 - Gojko Adzic on designing product development experiments with Lizard Optimization * #24 - Frontent Architecture, Backend Architecture or just Architecture? With Tomasz Ducin * #25 - Applying Observability: From Strategy to Practice with Hazel Weakly * #26 - React Query: A solution for Frontend State Management challenges? With Tomasz Ducin This is a public episode. If you would like to discuss this with other subscribers or get access to bonus episodes, visit www.architecture-weekly.com
Audio and video play straight from the show's own hosting. PodSubs stores and serves no media.
Transcript
From the show. Tap a time to play from there.
SPEAKER_00Hello, folks. Welcome to our next webinar. This time again, we have our special guest, Tomek Ducin. Tomek was a guest in the past. We were discussing whether we have front-end architecture and back-end architecture or just architecture or jokes aside, whether the perspective of the back-end and front-end people is
different on that.
SPEAKER_00So I encourage you to watch it. But even if you didn't, then today we have a bit different topic because the past recording was more high level. And today we will be more hands-on or at least Tomek will be more hands-on. I will be more watching and asking stupid questions.
technology or approach, Tomek will correct me definitely, which is called React query.
SPEAKER_00And this is, we believe that this is a really interesting way or again, bridging the front end and the back end and dealing with one of the most complex part of front end architecture, so state. Tomek, did I make it correct? Yes, yes, yes. More or less, yes.
SPEAKER_01So first of all, hello, everyone. And thank you, Oskar, for inviting me. So yeah, I'm really excited to be here again and to speak about React Query. So technically speaking, we could say that React Query is a library or actually a set of libraries because it's been like, It started as a thing that is specific to React, but it was kind of redesigned to be a core library,
SPEAKER_01just framework agnostic, and now it has adapters for React, Angular, Vue, Svelte, and probably something more. But generally, the logic, the pattern, the design is like, yeah, 95% the same. You just adapt it to different frameworks. So obviously, if you learn it once, then like, you know, moving from one framework to another, the concepts won't change. Yeah, so the whole thing that you said,
SPEAKER_01Oskar, what is one of the most difficult things in front-end development is state management. So we could kind of divide this topic into two smaller subtopics, or at least it's very useful and effective to do this distinction. Yeah. into client state management and server state management. If we don't do this distinction and we don't even think about it, then obviously things get intertwined,
SPEAKER_01mixed, and it will be definitely more difficult to maintain in the long run. So all in all, when we create client applications, actually, it doesn't have to be web. It could be even put, if you have any requirement, even in web mobile applications as well. Or even port it into native ones if you have a reason to. Because the whole point is that the client application...
in order to show something on an interface to the end user, it needs to get some data. Most probably this data is not hard coded into the application itself, obviously.
SPEAKER_01Like you could have obviously things like, I don't know, SQLite or any kind of local files that would have something. But most of the times the client app will need to reach out to some external data source. And there is, it seems to be quite an easy topic only at first. Like you just fetch the data, then you get the data stored locally and display it. Then you're allowed to, I don't know, modify it,
SPEAKER_01delete, update, whatever, just run the crude operations. But there are lots of low-level edge cases or problems that we need to take care of. And if we don't, then we will get lots and lots of lots of problems. So the whole point of React query, or actually this abstracted away from the framework, the tan stack query, it's from the tan stack group of libraries, whatever, is to... focus on this specific topic,
which is managing the server's state on a client application.
SPEAKER_01So do only this very specific thing, but do it very, very, very well. So comparing to multipurpose tools like Redux, MobX or any other state managers that we have in JavaScript or generally the front end framework, it doesn't try to be a multipurpose tool, which is, in my opinion, a very good, let's say the result is very good. The outcome is very good because if you try to be good at everything,
We have a saying in Polish, if something is for everything, then it's for nothing.
SPEAKER_01It's good for no use cases. So if you try to be a multipurpose tool, then you cannot really fit a very certain use case because the question is, what is your abstraction? If you have a situation where you are dealing with lots of nested and complex and reactive forms, this is one case. If you have real time data that you would need to update in real time,
SPEAKER_01or if you just wanted to show, I know lots of tables, lots of charts, listing, et cetera, these are totally different use cases. And if, for instance, Redux tries to be a multipurpose tool, handling both the client state and server state, etc., it cannot provide very specific abstractions for very specific use cases because they would not fit the other use cases at all. So, of course, we could provide libraries that it could make it more specific,
though...
SPEAKER_01This is not how people use Redux, and most often people just put everything everywhere in Redux, and it doesn't help to enforce any kind of key to modularization. Redux, in theory, seems to be very cool and nice, and it has lots of advantages, though in practice, pretty much in every project I have been consulting, there were... There were lots of doubts on how people chose to use Redux.
Pretty much there was no boundaries between what should be kept where, etc. Like handling one thing in multiple places which lead to desynchronization. On the other hand, if you try to synchronize things by normalizing your Redux state, then there was too much coupling between modules and like whatever you would do,
SPEAKER_01you would fall into some issues. So on the other hand, React query is trying to focus on only one thing and do it very, very well. The server state management is essentially loading the data from the external data source and allowing the pieces of your application, the visual components, the UI components, to consume them in any way. Most usually it's going to be just displaying the stuff, allowing to update them,
SPEAKER_01allowing to delete, whatever. And I mentioned that there are lots of small things that we would need to take care of. So first of them is sharing the data. For instance, if you walk into a certain page and you walk into another page and you walk back again, now, should you see the data that you have already loaded or not? without having any state management solution,
you would need to figure out this thing. But also something that front-end developers are not really kind of aware of naturally and something that I believe backend developers are way more aware of is
SPEAKER_01that whenever we pull the data, from a server to a client, then we should assume that hypothetically, this data is already stale. It could be. Not always, because there are things like a list of countries that will not become stale very soon, right? But generally speaking, by the time that we receive the response, it could have already changed on the server,
SPEAKER_01especially when we're using any kind of pool-based approach. And without using something that is specialized in synchronizing the server state with the client, it's very, very rare that people would think about this, that there is some kind of refetching or that the data that we load has some time to live. I wouldn't be so optimistic about the backend developers
because that's also an
SPEAKER_00issue when you are working in like distributed environment. Then I'm afraid that unfortunately many people also believe that if they got some data from different service or different module, by querying or even by getting some messages like events through the queue, then that's like a current state that they can make your decision based on that. But as you described, it's not how it is because in the meantime,
SPEAKER_00there is always some latency and that can change. And as you said, not always that's an issue for countries, probably. Luckily, that's not happening too often that we are getting new countries. But if we are in like a high frequency trading, then definitely that's really important.
SPEAKER_01Yeah, that would question whether HTTP is the way to go in such a case. But putting that aside... By the way, implementing something like a time-to-live feature or whatever we would call it on the front-end site, well, maybe it's not rocket science, though. This would require us to design the solution, to implement it, to test it, to abstract it away, to think about what should be the API surface.
SPEAKER_01There is quite a lot of things that we should take into account. Also, there is a pattern, an approach that is called stale while revalidate, which essentially boils down to showing the old data or the data that you have already loaded for the user of course this relates to interfaces so when you go back to the page on which you have already been before and you have loaded the data the question is
should you let's say show a spinner but there is no data that is displayed in the meantime but there is another possibility that you could show the old data just so
SPEAKER_01that the user can take a look at it Because first, this is not really probable that the data would change very significantly, or quite often it is also not probable that the data would change at all, right? Because we need to emphasize that it is a hypothetical staleness of data. We don't know until we check it, right? So the thing is, it just provides better UI, sorry, better UX,
SPEAKER_01if the user can just take a look at the old data. We show stale data while the engine revalidates in the background, like refetches. So this is called swr stale while revalidate. Of course, React query is not the only library that is implementing the approach. And it's not the first one that implemented it. But again, this is yet another thing that you don't need to think about. It just automatically baked in there.
SPEAKER_01So yeah, we share the data across multiple components whenever we want. The thing is, the one question which I'm going to address slightly later when we go further to the code is, How much of the data that we load from a certain endpoint should be available in other parts of the system? So how much should be shared, generally speaking? How much should the data be local or how much should it be global within the application?
But this is going to be answered in a slight different approach because we're not
SPEAKER_01going to say it is global. We're not going to say it is local. It depends on a slightly different factor that we'll discuss later. So caching is one thing. Sharing is another thing. Time to live, or actually how it's called in React query, it's stale time. It's yet another thing. Or there are actually two... parameters that we will see later, there is also a GC time, garbage collection time. So there is a time after which it passed,
SPEAKER_01the data is considered stale, but there is another threshold after which the data is considered kind of so stale that it would be even kind of dangerous to show to the user so it would be removed entirely automatically so think about by the way if we have the second zero and we load the data and let's say that we have configured the stale time which is the time to live or let's say five thousand milliseconds five seconds
and we go to another page and we get back after let's say three seconds now we have fresh data cool now we go out and we get back again now the five seconds let's say
SPEAKER_01let's assume that it has already passed Now, there could be a timer that is waiting to count whenever the data would be considered stale or not yet, but it could have already, the timer could be already removed because the data has been set to stale. And imagine how many race conditions we would need to check here. Like, of course, it's not a rocket size, but imagine all those freaking unit tests with mocked timers how much how many
mistakes people could make and this is something that is essentially baked in like imagine like if you need to refresh the data or if you need to remove the data after some time has passed etc
SPEAKER_01like most probably many teams would just not do it Because of the complexity, because of the cost of maintenance, because of the cost of testing, because of lack of ability to do that, essentially. So this is only the tip of the iceberg, what I said. So there is way more things here, like... It's very easy to provide pagination here, to provide filtering, sorting, to provide infinite queries. Like on social media,
when you scroll down, you have this infinite wall kind of pattern.
SPEAKER_01Yeah. We have automatic refetches in the background. So the stay while revalidate mentioned already. Basically, whenever we get back, the user can see if there was something there. Of course, it can be turned off if we want. So this is highly configurable. But also, if we get back to a page or to a component, to a view, whatever we call it, and there is an active subscription to a data set that is already stale,
then the refetch is taking place automatically.
SPEAKER_01Because why not? Because this is what we would expect. And this is what makes React query a declarative API. So whenever we have a component that needs to display some data, I like to think of the query pattern, the query just from the name of the library, as a dependency. So let's say that you could have in React like something that depends on the props of a component, something that depends on the state,
or I like to think of the use query hook because this is what we're going to see in
SPEAKER_01a while, that the component depends on external data source. Now, whether there would be a side effect that would actually shoot an HTTP request or not, well, that depends on what is the internal state of the cache of React query. so yeah there is caching there is cache invalidation background fetching refetching refetching also when we fetch the data there are six different states uh in which the a single query uh could be in so speaking very simply it
could be loading error
SPEAKER_01or data loaded but uh so these are the three most classical ones but It could be the initial loading or it could be any of the other loadings. And they are different in a way that when we load for the second, third, et cetera time, then we do already have the data that is available. So taking those edge cases, there are more than these, and there are just six of them. And we are using TypeScript union types,
SPEAKER_01discriminated unions, which allow us to check that if you are initially loading, then you cannot have the data. Because how come? Or if you're in an error state, then you don't have the data and you're not loading because you're in error state. So this is kind of very, very typical usage of discriminated unions. And again, If you use React query, then you're simply using this data loading state machine. Essentially, this is a very, very simplistic implementation of a state machine.
SPEAKER_01And as I was doing trainings for several years already, all that I could see in people's projects was that you had a component and never mind whether it's Angular React or whatever. There was a loading Boolean property, there was, or hook, whatever. There was a data, which is most often an array of something. And there was the, sometimes, not always, the property for the error. And the problem is, most often people create them as three separate properties.
And it was kind of eye-opening for people to figure out that this is a very,
SPEAKER_01very, very bad approach. Because if you have, let's say, for loading, you have two states, which is either you are loading or not. So two values for the Boolean. Let's simplify that for the error. You also have the two values. Of course, there might be many different types of errors, but either you have the error or not. or again, simplified values for the data. Either you have it or not. Again, there could be way more, but it's two multiplied by two multiplied by another two, which gives us technically possible eight states.
SPEAKER_01Now, how do people transition between the states? Well, manually updating property here or property there, forgetting about this, forgetting about clearing that, forgetting about doing this, this and here, which introduces lots and lots and lots of bugs that people are not even aware of. So we could have in this classical example, eight different types of states, And most often the overall of the correct states is only three,
which means five states are impossible or like logically they should never take place. But the type system or the solution allows to define them because if they are three
SPEAKER_01different properties, let's say on an Angular component class, then they exist independently on each other. Or if you have three different use state hooks in React or in Vue or whatever, then if they are independent, then they can change well independently on each other. So what would be the solution? To create an object, a single property, that would be an object type, or a single use state hook or a single whatever you're using, whether it's even in Redux, Jotai,
SPEAKER_01Zustand, nevermind. make it an object which would be of a union type. Now TypeScript would require you to provide all the required fields of a certain type. It would disallow you to create the properties that should not be here because of the excessive property check and other edge cases. And when I was showing to people like why don't you just introduce a simple union and you will see
how many bugs you've
SPEAKER_01been having, but nobody submitted them or nobody noticed them. They just work incorrectly. And that was kind of eye-opening, like, wow, how cool is that? Now, in React Query, It's just there. It boils down just to creating a specific if statement. You just need to guard against a specific property. For instance, it's loading or it's fetching or if data is there, et cetera. But essentially,
SPEAKER_01thanks to the fact that React Query is using the state machine, you cannot basically break your runtime, which is absolutely awesome and cool. And again, you don't even need to, like, even if you don't care about design or developers in your team and your company don't care about the design, they just want to ship stuff. If you kind of force them or convince them to use React Query or any of the Tanstack Query libraries, then you can rest assured that there would be no silly bugs related to incorrect state management of this loading
error data loaded states
SPEAKER_01in your application. So imagine you're just using a simple library and we will see this in a while that there is a very, very, very thin overhead on the code that gets you so much work done. Okay, so let's assume that the sales pitch is already done and we can jump into the code.
SPEAKER_00Could I do a quick recap so I'm sure that I got it? So React query is like... In theory, it can be seen like, how hard can it be to just query backend from frontend to get the data? But of what you described, then there is a huge amount of possible accidental complexity that not necessarily we would like to live with,
SPEAKER_00like caching, retries, requering, invalidating cache. or even with now our current single page application work where we are going to other page and going back, then not necessarily we are actually going to other page, just staying in the same context and then figuring out what to do with those page transition. And all of that, it's kind of like, let's say, boring code.
SPEAKER_00Boring by means that that's not something that you would be typically want to be doing. Or even if you as a developer would like to be playing with those issues, then not necessarily your company should be paying you for doing that.
SPEAKER_01Certainly. Absolutely, yes. I would just add to it. Absolutely, yes. I would just add to it that it's not about only the edge cases, but also what you mentioned. So these are the potential bugs that you might need to fight. These are the features that you need to have, like the refetching thing. And these are the, let's say... eliminating errors like these state machines. So not something that you would like to guard against,
SPEAKER_01but essentially eliminate the error entirely. And this is what is done. So there are lots and lots of various stuff. Unfortunately, from what I saw in real production products, is that people rely on, sometimes on promises, sometimes on async await, at least in React applications. And sometimes you have something in the try catch, the catch clause, there is any,
SPEAKER_01sometimes there is something more than console error error, sometimes not.
SPEAKER_02Yeah.
SPEAKER_01So imagine, what are we talking about here? This is unfortunately the state of, this is the reality right now. But generally, error handling is not something that people pay attention to, unless this is explicitly stated, I don't know, in user stories, in acceptance criteria, in definition of done whatever. whatever we call it. So, yeah, to summarize, to recap, yeah, lots of stuff that
SPEAKER_01that will need to be, that will be basically taken care of, yeah. So I like to draw things, so I'll try to quickly draw basically what is going to be the general, let's say, flow of the application. So just let me know if you can see my screen and if it's clear. Can you see? Yeah, I see it.
SPEAKER_00I see it.
SPEAKER_01So, yeah. So let's say that here, I'm just quickly... creating a tree of components. So let's say that there would be some of the components over here. So this is just going to be a tree structure that would resemble how our components would be put in some kind of a hierarchy. So this is the root component, which has two children, each child has its own children, blah, blah, blah, blah, blah. So one thing that we want to have in our application,
SPEAKER_01and again, this is kind of, we are going to take a look at React, but this is framework agnostic. We don't want to be kind of forced to put some data. Let's say that the data is in blue color. We don't want to put it on a very specific component because at some point we would like to break this component into smaller ones because we want to make it more maintainable. The component, let's say, crossed 300 lines of code and we just decided that it's doing
too much and we want
SPEAKER_01to break it, et cetera. So we want to make kind of moving the ownership of the data as fluent as possible. So all in all, none of these components is going to be the owner of the data. So that data is going to be put somewhere elsewhere. So natively, if we are using private state, then there would be something like use state or use reducer. So certainly we are not speaking about something like that. So there would be something in React available via a context,
React context.
SPEAKER_01So in this case, there would be basically a query client available within the context technically. So technically it's a context, but I'm going to refer to the React query, let's say, terminology. So query client is basically the single, it's a singleton. We could say it's a kind of a manager that will do all the stuff that you don't
SPEAKER_01want to care about. So all in all, a component is just going to say, I want to use a query, just like we use state, we use effect, use reducer, et cetera. So a component is just going to say, hey, I need some of the data. Of course, it will have some parameters, but still it just says, OK, I want to have a query. Now, since useQuery is a singleton, then we are expecting that there would be some context that is
basically wrapping
SPEAKER_01the whole application, because why not? putting it globally. By the way, singleton is considered to be something very bad in backend systems quite often. And this is reasonable. On the other hand, what is a bad or good practice on backend could be totally different on frontend. So having singletons on frontend doesn't have to be a problem. And in this case, it's not a problem. Basically, you want to have a service that is available within entire application.
SPEAKER_01By the way, most of the services that you might want to get access to via dependency injection, they're also going to be singletons. Like in runtime, at least. So by the way, you can think of the context API Technically, it's slightly different, but you could think of it as an alternative to dependency injection. Some people could quarrel whether it's more a service locator or dependency injection. Let's put that aside, but it is kind of an alternative to it.
So all in all, on the component level, we're just going to say, hey, I want to use a query.
SPEAKER_01And that's it. And now this information walks into the query client. Now the query client, let's say that this is the boundary between the client and the outer, let's say, network. Essentially, this is going to be a server here, obviously. So this would be our server API. And when the query client, you can quickly guess what is it going to do.
SPEAKER_01So there would be a query cache over here. I'm going to make it red just to distinguish the colors, query cache. So the query client is basically asking, hey, dude, do you have this data already or not? Is it stale or not? Has it been removed or not? Et cetera, et cetera. So if the data was not there, then the query client would decide, okay, so now we need to do the actual HTTP request,
SPEAKER_01obviously. Now when the data is being returned, the query client essentially puts the data over there. So let's make it with a solid green color. And this is one cell within the query cache. So this is going to be the query response. And from now on, of course, this is going to be then returned over here. But this is a subscription. So this is a, let's say active,
subscription or maybe I would remove it from here just to make it slightly smaller to make it more readable and what is what happens automatically from now on is that when other components would try to ask using the same use query hey dude do you have this data then what query client is going to do is first ask the cache so now
SPEAKER_01the data in the cache could be fresh which is basically here you go dude This is one possibility. Another possibility is that it became stale. So it's not fresh anymore, but it's on the other hand, it's not that bad that we had to remove it. So in this case, what we would do would be the stale while revalidate. which is essentially, okay, dude, we're going to give you what is the old data, but in the meantime, we're going to ask the server for what is the most recent data,
SPEAKER_01and whenever this becomes available, we're going to simply replace it. So it's simple as that. But imagine, as we said before, all these small edge cases, all the small mistakes, errors, et cetera. So the mechanics is not that difficult, though it's not really simple to implement it.
SPEAKER_01And I would even say it's even more difficult to provide a nice and useful API. Like, how do you craft? What are the public methods? I'm speaking not about creating applications, but creating reusable libraries. Designing APIs is difficult. This is the problem. If somebody was working on a library, something that was reusable across different use cases, then you know what I mean. Currently, we have version 5 of React Query, which is very, very mature.
SPEAKER_01By the way, React Query, my guess is that it was started kind of at least in 2018, maybe even earlier. But you can imagine like after seven years that this is so...
SPEAKER_00Yeah, especially in the front-end world.
SPEAKER_01Especially in front-end world, yeah. Yeah, so what is really cool, we're going to see that useQuery is accepting very few parameters. So it has kind of 20 or even 30 parameters, but most of them have extremely well, well, let's say, carefully chosen defaults. So you have tons of parameters or configuration, but most of the time you're just going to put two into your query,
SPEAKER_01which is what is basically in the cache. You need to have a key in the cache, right? Like where is that data that I want? So essentially the key, this is going to be one parameter that you would always pass. And the other thing, which is what is the HTTP function? So how do we actually run this request? And these are the only ones that you are going to put most of the time. So this is the general, let's say, diagram.
SPEAKER_01And before we run into the code, Oscar, yeah, would you like to comment on anything or destroy this?
SPEAKER_00No, I think I really like it to be true. I think that... such design, if there were such libraries or software backend, then it would be super useful, like even for the communication. Because as you said, being declarative and saying like, hey, I want to call this endpoint, whatever it got stale or then please do it for me. I just want to get the data. Then it's much easier to reason because,
you know, I'm in the EDA and messaging court and I'm not saying that message based communication and even driven communication is hard, but definitely it's enough different that many people are struggling to reason because,
SPEAKER_00you know, I need to react to this. I need to handle that. Then I need to process this and that. where they actually, what they want to have is like just performing the operation and getting some result, either getting data or running some business logic. And here it is nice because you're actually saying, yeah, I want to get this data, please give me. And yeah, I think it's pretty sneaky design,
SPEAKER_00especially that it's kind of like a publish subscribe behind the scenes. But the API is hidden. So it's like a request reply pattern. So messaging behind the scenes. having in front of like, just give me this data. So my question is, I'm not sure if you will be covering that, but are there any recommendations for the HTTP endpoints to
provide some headers
SPEAKER_00like caching headers? Or do you know whether there are some recommendations to make the React query more efficient or easier to handle?
SPEAKER_01By headers, I guess you mean ACP headers. I would say How you keep your local state on the client side, it's kind of up to your implementation. So I would say the headers that you sent is a part of the contract. So this is not something that you could, you know... change only one side. But I would say that whatever your contract is, basically stick to it.
SPEAKER_01And React query would basically have to adapt to it. So I would say there are no recommendations. But don't treat React query as anything that relates to the contract. Like headers are the primary source of truth. And only then React Query could do something here. But all in all, yeah, I would have a lot of recommendations, actually, but we will go through them on our way.
SPEAKER_01Okay. Commenting on what you've said, that there is a PubSub, absolutely yes. I would generalize this statement to say that actually every React context is a PubSub. And if we think about alternative state management solutions in React or in other frameworks, it's difficult for me to say that each of them is a PubSub, but I would say that 99.9% of them are publisher subscribers
because client
SPEAKER_01applications are extremely reactive. Now, I can imagine that there might be a backend developer who was doing the same stuff or similar stuff for 20 years and a person could not even understand what reactivity is. On the other hand, on frontend, it would be very, very, very difficult to be anyhow productive without even intuitively trying to understand what reactivity is about. So kind of reactivity for us on frontend side is bread and butter. So,
and the PubSub is such a simple pattern that it's pretty much, I would say, everywhere. By the way, in backend logic, quite often services need to interact with each other.
SPEAKER_01Then the question of coupling kicks in. And we have a very similar, let's say, problem to deal with on frontend. And this is actually a comment aside from React query. We don't want... components to communicate directly between each other, because that would be a killer. Because on frontend we have way, way, way more. I know two orders of magnitude, more components than services on backend side, or three orders of magnitude,
SPEAKER_01that would be an absolute killer. So we never communicate with each other directly, apart from the parent-child relationship where we just pass props. So this is the only exception from that. But whenever we want... something that happened here to affect another component, then a PubSub is the obvious solution. The question is just which implementation of PubSub is it going to be? So query client is a PubSub,
Redux is a PubSub, MobX is also a PubSub, and so on and so forth.
SPEAKER_01So yeah, lots of PopSubs everywhere. Like this Toy Story meme. PopSubs, PopSubs everywhere. We could say. Right. So there is also one nice thing that I haven't mentioned, but this is just a kind of logical consequence of this whole approach. Is that, let's say, there is no data, there is no... None of the components wanted to actually fetch anything from
our query client.
SPEAKER_01So let's say that I'm just going to leave them here, those rectangles, but I just made them empty. And what I would like to show you is the varying number of subscribers. to this query client. So obviously the subscription is not kind of global. We're not counting the global number of subscriptions, but it's a subscription pair query key,
SPEAKER_01obviously. And what happens here is, let's say we're starting with no subscribers for anything. And this component is being displayed or is becoming active as the first one. So we have then, let's say for key one or key A, we have a number of subscribers that is moving from zero to one. uh of course that would be actually being stored uh over here
so here we would have the number of subscribers and here we would just have the data for this specific query and let's just let me just move this so that we just make it a key b just to
SPEAKER_01determine that there are multiple keys And query client figures out that the data is missing. So it, oh, sorry, sorry for this. So the query client would just have to shoot the request to the external data source. It would get the data. So here we would get the green one over here and the component gets the green one. Now the thing is,
When would be a potential moment for the query client to rerun the query?
SPEAKER_01Let's say that we drop the subscriber. So here we would drop over here. So obviously there is zero. So query client, even though the data is fresh or after some time it becomes stale, obviously, If this becomes stale, query client is not going to refetch this data because nobody cares about it right here, right now. So the question is, when would it actually happen? So,
of course, there is a possibility for us to code this or to configure it.
SPEAKER_01Like, please refetch in the background because there is a very high probability that people would want to go back here and we always want to have the data fresh. This is absolutely doable and this is simple to do, but this is most often not the case that we want. So all in all, the moment when the data is being refetched again is when there is a new subscriber coming in. So let's say that we walked here and let's say it was green again.
SPEAKER_01And after some time, the data collection became... Oh, sorry. The data collection became... stale, let's say. So this is yellow. And right now it does not revalidate again. Of course, we could, again, configure it to have a different behavior. But when a new subscriber kicks in from over here, then this is the point that query client is making the if
statement to potentially
SPEAKER_01rerun the query. So again, there are lots of, you know, edge cases that even what we discussed so far, we don't see them yet, but they are really, really important. So when the number of subscribers increases or decreases, when it drops to zero, etc., like all these edge cases are being covered, considering that there might be lots of race conditions.
SPEAKER_00Yeah. It's intriguing, again, that how big overlap is between backend and frontend and how the patterns overlaps. Because for instance, I was writing about the connection pool. and how connection pool internally usually works as like a single queue per query string, then here it's the same logic. So you need to ensure that you are not making double queries, et cetera,
for the specified
SPEAKER_00connection with the database, and here it's a really similar concept. Yeah,
SPEAKER_01because if a similar problem is being solved, then if people who cannot talk to each other for any reason think about the problem uh for long enough they kind of emerge to the similar uh similar solutions yeah so let's take a look how this looks like um so that would be an example let me just um let me just see something So the application,
I've got a simple application here that I'm using on my training.
SPEAKER_01So here is just some data, sample data being fetched. Here we've got a listing. By the way, what would be a good use case for using React Query? Actually, like generalizing. Everywhere where you need to load the data and to display it or do anything with it, but especially, absolutely especially when you have listings, kind of data tables, searches, filters, pagination, etc. These are absolutely marvelous use cases for doing it, which is still...
SPEAKER_01Most of the applications that we do there, for instance, in Uber client, I would not necessarily do it because there is too much data that changes in real time. That would not be a good use case. On the other hand, if only you have such pages like this one, like with kind of sophisticated filters, et cetera, and you do lots of network requests, then yes, this is absolutely a perfect use case.
SPEAKER_01OK, so we've got everything up and running. I would just increase the font size. So here I have a box with some simple filters or advanced filters, and I have just some listing of tiles with some data. So let me just take a look at the employee data. So what we're doing first is we're importing the use query from can stack slash react query. So this is basically the react adapter for the can stack query.
SPEAKER_01And let's jump into use query where it's actually being used. So this is our function. So I'm just going to drop query function for now. And let's ignore the placeholder data as for now. So this is the number one thing that we always need to define. And the query function is the number two thing that we always need to define. Now, we mentioned that query key is the thing that will allow us to
identify which query
SPEAKER_01resource, which piece of data is actually which. Kind of obvious. Now, you could think that the key could be just an ID. Now, this wouldn't be really useful. So in our case, the key is not an ID. And I would say this is one of the best ideas in the implementation, the technical design in React Query, is that keys are hierarchical. So in other words, that means that a query key is going to be an array with
positional pieces of the key.
SPEAKER_01And now we can automatically do pattern matching. For instance, there would be situations in which you want to prefetch not just one key, but a whole range of keys. Or you want to refetch, prefetch, invalidate, remove, locally update them, and so on and so forth. Because you can basically get access to them, and we will be doing this.
SPEAKER_01And the query key, first of all, this allows us to access, like identify the thing, but also there is one thing that we haven't mentioned, and this is a mutation. So all in all, in very short, we'll cover this later. When we get the data, it could happen that, let's say, I would fetch a list of elements, just like here. And I have, yeah, employee skills, blah, blah, blah, blah, blah, get 200, okay.
SPEAKER_01And if I click the trash icon, the delete over this element, Leah71, whatever, marketing, then if I remove her, then this is the delete that succeeded, right? Delete 204, no content. And I would like the query to be rerun back again. So this is also kind of taken care of here, which is this is what makes it even more awesome.
SPEAKER_01And so all in all, after the mutation, so let's say that the mutation is just going to run the HTTP delete. But the thing is, we might have just the first page of all the employees. This would be one key. It could happen that, let's say, I wanted to get the employees only from one department, and this would be another query. which would have another query key, right? By the way,
here we've got the funny beach icon where we can see all the queries that we've got here,
SPEAKER_01which is yet again, like a perfect developer experience. So on a null, we've got the employees over here. This is the first element. And then the second element is actually a big JSON that includes a long... It's just a dictionary of the filters. So here we are filtering by the department. So the strategic management is just the department ID one. The search term is empty because we haven't put anything inside
this input over here.
SPEAKER_01Skills filtering is set to any. We could also make it into all. Now we can see that the skill filtering has changed, whatever. So, all in all, when I delete, let's say, this guy over here, then the question is, what keys should get affected? And this is this really cool thing that if let's say I want to, oh, by the way, what we can see over here that when we delete an employee with
a certain ID, then I would like to potentially invalidate all the query keys that just start with
SPEAKER_01the employees part. invalidate means mark them as stale. Don't remove them yet, just mark them as stale. Because, by the way, if I remove an employee with a certain ID, which query keys get affected? Like, I don't know until I check them all, right? Now, optimizing to update all the keys all the query keys, like, sorry, all the data that rely under the keys that start with employees,
SPEAKER_01that might be efficient, but on the other hand, that might be also kind of overcomplex and just unnecessary. So we can just, this is the simple thing, just mark them as stale so that if only your key starts with this, just mark it as stale. And this is like... This is correct. This is simple. Maybe this is not the best efficient, but still good enough in most of the cases. However, we know that if you had details of a certain employee, right?
SPEAKER_01Then we know that for this one, this... resource doesn't exist anymore. So it doesn't make sense to invalidate it. It makes sense to remove it entirely. And now architecture wise or design wise, this is up to us. How do we design the keys? Because how do we design the keys is going to reflect how does the mutations change the keys, the hierarchy, the structure that we've got in our application.
SPEAKER_01And what does this depend on? On what are the operations in our system? So actually from technical perspective, as you can see, this is not that kind of complex, not that difficult, no rocket science. Though what you should really pay attention to in practice is how do we design query keys? So let's say that the default approach would be that if you have a resource, let's say like these employees over here,
then we could have a resource for a list or we could have a resource for details.
SPEAKER_01So copilot kicks in over here. So if I have just a key that looks like this, it means that there is only one key possible, which is not the case because you might want to have, let's say, page one or page two. So these are totally different keys. By the way, these are all totally different keys. Now, this one does not make sense because if we have resource details,
SPEAKER_01then details of which actually resource. So we are missing, obviously, the ID. So here we would need to have, yeah, exactly, like ID1 or ID whatever we've got here, or even to put a, I don't know, let's say that this is an ugly UUID. And right. So again, now in terms of the list, in our case, what we're doing here is I don't have pagination over here yet. And I don't have a sort because I've got this on another branch,
but it doesn't matter.
SPEAKER_01Let's say that we have pagination filtering. sorting, etc. So we could have filtering by this input, by this multi-choice thing, by salary range, by the number of skills. Let's say that we would have some JavaScript. Oh, nobody with JavaScript. Whatever. Never mind. Here we've got JavaScript. Maybe I've got this on another branch. So all in all, the thing is,
SPEAKER_01would we put pagination over here and filter, let's say, skills filter over here? Well... Actually, not necessarily, because why would pagination be before the filters? Like it should be on the same level. So all in all, this is kind of the most typical approach where we've got the resource, whether we have a list or not. And then comes a whole dictionary of the parameters. And this is actually the thing, right? We've got the employee name filter,
SPEAKER_01the department filter, skill, skill, salary, salary, salary, et cetera. Now, the get employees function that we can see on the right hand side over here, let me just close this one is a very simple, this is the build search query. This is Axios based. So here we are running API client with some automatically generated TypeScript types from a open API contract.
So here we've got the response body, which essentially boils down to an array of employees. This is the URL, and these are the parameters from a URL search params, I believe.
SPEAKER_01And so this is just an HTTP function. It accepts the criteria, which is, again, a... a dictionary. So we could take a look at how this looks like. So this is the employee, blah, blah, blah, blah, blah. Again, generated automatically from the contract. But yeah, the URL is somehow connected with what is going to be our key. By the way, technically speaking, if only we have a different key,
SPEAKER_01then this is a totally different resource. Totally different, let's say, cell of data. So these are the two properties that you are going to put into your query. Now, we could determine that the stale time, let's say, would be this amount. So what Copilot suggested me would be five minutes. if I'm counting correctly. So after five minutes, the data would be considered stale,
not yet to be removed. If we want the data to be removed after five minutes, that would be GC time.
SPEAKER_01We can, of course, create, specify both. Now, it's not the case that GC time always needs to be bigger than stale time. It depends on your use case. There are situations where stale time, sorry, GC time could be smaller than stale time. This really depends on what you need. And also the placeholder data is basically whatever we want to show when we get back. And we had already this key so this is basically whether we want to show
what do we want to show in the background so i can by the way um display what is going on here so i'm going to reload the page and we would see from the beginning what are the keys that we'll have so employees essential is essentially what we've loaded over here and
SPEAKER_01the departments one is uh the feed for this multi-select And by the way, we can also see, oh, I want to close this one. We can also see that there are two requests over here, the departments one and the employee skills. So if I move, oh, before I move, we can also see over here that there is the colors. the green for fresh, blue for fetching, violet for pause, and stale for the two queries.
SPEAKER_01Now, there is also the number one over here. The number one is the number of subscribers. So essentially, our employee list component is the only subscriber in this case. Though, if I created more of these components, then we would see the number two, three, four, or whatever. Now, if I type something here, like I would write John, for instance, I want to see all Johns. Then again, depending on what is our application logic, we can see that there was search term G,
SPEAKER_01G-O, G-O-H, G-O-H-N, John. And as we can see, the last one is being used. So there is one. And the other ones, well, they have been here. but they are just kind of inactive. We could say this is an inactive state because there are no active subscribers. When they reach GC time, they are immediately removed. Obviously, this is possible from the DevTools to automatically refetch
them whenever we need it.
SPEAKER_01We can reset them. Reset is basically make this query key move to the initial state. which often boils down to the same thing as invalidate. We can remove it or we can even technically force it to restore loading. Like we can do lots of things over here or we can just hardly remove it. Now, this is stale because...
SPEAKER_01automatically or by default, the query keys stale time is set to zero just to denote what we have said before, which is by default treat everything as stale because the lesser evil is to make more requests but show what is kind of up-to-date rather than show outdated data for the user because the
developer didn't know how
SPEAKER_01to implement it correctly. And when the developer would see like, why am I doing so many requests? Probably they would find out, oh, there is a stale parameter over here so I can just configure it, right? So again, this was being carefully kind of chosen what should be the same defaults. Now, if I move out, I'm deliberately moving out just from the tab, or I can move out into a different window in my operating system.
SPEAKER_01And I go back, you would see that this was reloading over here. I can try to make it once again. Yeah, but it would need to wait for some more time. Because when there is an event in the browser, not sure what was the name, on load or on focus, basically when your browser tab gains the focus back again. This is also a possibility. So not only new subscribers, like new components subscribing the key, but also the browser regaining the focus.
SPEAKER_01Like this is essentially all the use cases that we need to have baked in. So this is so much like so, so useful. right and um yeah um there is way more things that i could i could mention uh here by the way we can also take a look at what gets displayed over here uh maybe i'll just increase the font a little bit. So here with the departments query key,
SPEAKER_01what I can take a look at here is basically what are the observers. So there is essentially one observer, not sure why it's not displayed, maybe I'll just reload it. uh the departments observers for some reason the data about the observer oh here the observers is there is one observer over here also the gc time is set to a 300 There are query options, blah, blah, blah, blah, blah.
But also we can see what the data is being put here, like nothing that much. Nothing kind of surprising though, very useful to see what do we actually have over here.
SPEAKER_01Now, do you have any questions, Oskar, at this point?
SPEAKER_00No, I think you nicely explained it. I will have a question about how it is implemented in other environments like Angular that doesn't use this reactive use effects terminology. So is it like RxJS or so?
SPEAKER_01It's very similar, though... It's very similar. Let me just use it with inject query. Angular and version 5. Just one moment. So this is going to be very, very, very similar, though it's not going to use the use query thing, because in Angular,
SPEAKER_01we have an inject, which comes from not the React context, because there are no React context, we've got dependency injection in Angular. But still, as you can see, there is query key, which works exactly the same. The entire function is exactly the same. You can expect that all the parameters like stale time, GC time, et cetera, they're exactly the same. The only difference is that in Angular, yes, we have RxJS, Though Angular is moving to signals very, very, very strongly.
SPEAKER_01By the way, we could make another episode on this one day. Like why, what are the benefits, et cetera. So the things that are being returned from the query function and actually whenever we want to use any of the data over here is not being exposed just as ordinary properties, just as it is in React. because everything in Angular from kind of two versions or maybe three versions from now is being wrapped in signals.
So signal is a very small reactive primitive that gives you baked in reactivity in very short.
SPEAKER_01Imagine that you have all the reactivity in React. Like, you know, use state, use reducer, use effect, the props, memo, use memo, et cetera, et cetera. But you don't have to write all this stuff. Like you get the same thing, but you write way less. There is less space for making mistakes, less code to write. Basically, you don't have to be kind of, you know, functional programming aficionado to...
SPEAKER_01And you don't need basically to have a PhD in functional programming. You just write stuff. And this is what signals are. So signals are really cool. So what Inject Query is doing is that it exposes everything as signal. By the way, in Angular internally, signals allow us to improve performance very, very significantly.
SPEAKER_00Yep.
SPEAKER_01So right now, this handles promises, not yet RxJS, but it's going to... By the way, Angular's adapter is slightly new. It's probably the newest, the youngest out of all of them. And yeah, when... This is just a matter of time.
SPEAKER_00Yeah, but it's nice that we see that it's really like cross-stack. But I mean, the patterns you described are quite generic. And as you show, the query by itself, it's not making any queries. It's just calling the specific function. Yeah, the function. So, yeah, cool.
SPEAKER_01Imagine how would you test it? You just put a function that returns mock. Yeah, yeah.
SPEAKER_00And you test it. And that's it. Yeah, it's a really sneaky design. I like it.
SPEAKER_01And maybe the last thing that I would mention, the delete mutation. So that's the one that we basically call, yeah, whenever there is a, yeah, the trash icon is being clicked. So the delete mutation is something that is not being handled declaratively because, well, actually, when would I run the mutation? Not when I display the component, when the user clicks. So this is imperative.
SPEAKER_01By its nature, it cannot be reactive. So we've got the delete. So when we click something, et cetera, whatever, we just need to run the mutation. So basically mutation.mutate, maybe it looks funny, but this is the imperative way to run the mutation. Now, going back to the mutation, again, we have a mutation function. We could also have a mutation key, but it doesn't matter. This is not required. So here we run just HTTP function again.
SPEAKER_01And if it fails, you can provide something. But if it's a success, then we get access to the query client. Who is a query client? It's basically this mediator over here, or as you said, PubSub. It's both a mediator, a PubSub, a proxy, an adapter, a facade for it. and a handful of other design patterns. So here we get a hold of it. And now if we want to mark something as stale,
then we invalidate queries.
SPEAKER_01If we want to remove something hardly, we can remove queries, but we can do way many other things as well. And that would be query client now. we can remove queries by this pattern matching. We could reset, which means bring them back to the initial state. We could set query data, which means If I removed a record, then I might want to go through all employees list query keys and only update them.
SPEAKER_01Sorry, that would be set query data or set queries data. Update them only locally. If your application is data intensive, why not? Oh, by the way, Copilot is suggesting me what could be the implementation over here. Yeah, it does. So probably missing parentheses. Yeah, it does make sense. So if it was not here, then just do nothing or otherwise just return a new array that does not include it. Now, what would happen is that you might have an array of 50 elements.
SPEAKER_01Now we would have an array of 49 elements. So this is what we would need to take care of. But imagine how many possibilities this opens.
SPEAKER_00Yeah, you could replace it with some placeholder, probably. Absolutely. On adding, you can add the row with just the data that you have on front-end site already.
SPEAKER_02Mm-hmm.
SPEAKER_01So this is really powerful. Now, for everybody that is either a front-end developer or an architect most probably, and you have some front-end stack, you can ask your developers whether your friends are using React Query, Angular Query, whatever, and if not, just suggest them that this is a really, really cool approach. I would say that for server state management, I cannot think of any better alternative.
SPEAKER_01And most probably if you've been using, I don't know, Redux or whatever for server state management and you try it out, you will not want to go back. Trust me. Yeah, I remember my past projects where I used Redux and it was like so much code to do.
SPEAKER_00So simple stuff. Yeah. To some degree, it was useful because you had those conventions, but then you need to hammer those conventions over and over again for all this stuff.
SPEAKER_01Yes, yes, yes, exactly. So yeah, I think that would be enough. So yeah, unless somebody would like to ask some questions that maybe we could make a follow-up, but that depends on how do you find this?
SPEAKER_00Yeah, so thank you, Tomek. I think it was enlightening. I really enjoy it. Before that, as you know, I just heard about React query, but I really liked the design. I even had an idea that transferring this approach to backend. So it's really sneaky. I like it. Thank you for doing this explanation, especially with those visualized visualization,
SPEAKER_00at least for me, that really help. And for the viewers, If you have any questions, leave them on the Architecture Weekly or just contact Tomek directly. Follow him. He does really great stuff and definitely you can benefit from even working with Tomek. And yeah, I think we can wrap it up. we can, as you said, get another round with a Q&A if people like it,
SPEAKER_00or if not, then as we discussed, like even you mentioned signals, that's a great stuff, or even maybe microphone sense. If you have some ideas that we can talk with Tomek that you would like to learn about, you know, front-end architecture, connection between the front-end and back-end architecture, then we are happy to record next episodes. Definitely, they will come.
SPEAKER_01There are actually lots of things that we haven't covered yet, which is, for instance, how would you combine React Query with Redux-based codebase or any other solutions? Or, for instance, how much would you share within the data? Or let's say coming from team topologies, how would we communicate? Or what could we actually fetch? Or should, let's say, one module of frontend use the data from one endpoint,
SPEAKER_01but could another, let's say, module of frontend connect to the same data? Like architecture-wise, like who could... fetch what actually or how much redundancy could we have over here these are like kind of more high level things we could do also an episode on comparing different uh yeah state management solutions yeah also so just suggest to everybody what is interesting to you
SPEAKER_00Yeah. Okay. Thank you, Tomek. That was a lot of fun for me and I'm sure that for the viewers as soon as they watch it. So thank you again and see you next time. Thank you very much. Thank you for listening.
SPEAKER_01See you, Oscar. Thank you. See you. Bye.
Welcome to the new week! “How to document systems build with Event-Driven Architecture?” and “How to keep our understanding about evolving messages definitions?” Are one of the common questions I’m being asked. For many...
Have you considered applying observability but struggled to match the strategy with the tooling? Or maybe you were lost on how to do it? I had a great discussion with Hazel Weakly about Observability beyond Open...
Welcome to the new week! For a long time, I’ve wanted to talk more about Frontend Architecture. In my projects, I always enjoyed delivering features end-to-end the most. That gave me the feeling of completing and...
"My favorite conspiracy theory is that the stuff we make in software actually has any sense. That's a big conspiracy, and you can see people believing that, and that's just not true. I mean, it is in some percentage,...
This time, our webinar has a special guest: Jarosław Pałka. He’s the Senior Staff Software Engineer responsible for benchmarking infrastructure in Neo4j. We discussed how to reason about performance practically, so how...