The Story of React Query

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
have you ever thought about why a specific piece of technology gets popular usually there's never a single reason but I do have a theory that I think is one of the primary drivers I call it the 5:00 rule with the 5:00 rule the level of abstraction for solving a problem will bubble up until it allows the average developer to stop thinking about the problem and therefore go home at 5:00 this is the story of one such example a story of how a single developer in a small town in Utah in his spare time created a library that is used in one out of every six react applications for context that means it gets downloaded 3.3 million times a week and has been downloaded 323 times since you started watching this that library is react query and in order to better answer how it allows developers to go home at 5:00 we need to take a closer look at what problems it helps developers to stop thinking about believe it or not that problem is react and to see why we need to go back to the basics in its most fundamental form react is a library for building user interfaces it's so simple that historically the entire mental model has often been represented as a formula where your view is simply a function of your application State all you have to do is worry about how the state in your application changes and react will handle the rest the primary mode of encapsulation for this concept is the component which encapsulates both the visual representation of a particular piece of UI as well as the state and logic that goes along with it by doing so the same intuition you have about creating and composing together functions can directly apply to creating and composing components however instead of composing functions together to get some value you can compose components together to get some UI in fact when you think about composition in react odds are you think in terms of this UI composition since it's what react is so good at the problem is in the real world there's more of building an app than just the UI layer it's not uncommon to need to compose and reuse nonvisual logic as well this is the fundamental problem that react hooks were created to solve just like a component enabled the composition and reusability of UI hooks enable the composition and reusability of non-visual logic the release of hooks ushered in a new era of react the one that I like to call the how the do we fetch data era what's interesting about all of the built-in hooks that react comes with as you've probably experienced firsthand is that none of them are dedicated to arguably the most common use case for building a web app data fetching the closest we can get out of the box with react is fetching data inside of use effect and then preserving the response with usate you've undoubtedly seen something like this before we're fetching some data from the Pokey API and showing it to the view simple but unfortunately this is tutorial code and you can't write tutorial code at work the most glaring issue is we're not handling the loading or error States this leads our app to commit two of the biggest ux sins cumulative layout shift and the infinite spinner the fix for this is pretty simple more State cool because we've used use effect to synchronize our local Pokemon state with the Poke API according to ID we've taken what has historically been the most complex part of building web app an asynchronous side effect and made it an implementation detail behind simply updating ID unfortunately even though this is where everyone usually stops we're not quite done yet in fact as is our code contains the worst kind of bug one that is both inconspicuous and deceptively wasteful Can you spot it whenever we call fetch because it's an asynchronous request we have no idea how long that specific request will take to resolve it's completely possible that while we're in the process of waiting for a response the user clicks one of our buttons which causes a render which causes our effect to run again with a different ID in this scenario we now have two Quest and flight and no idea which one will resolve first in other words we have a race condition to make it worse you'll also get a flash of the Pokémon that resolves first before the second one does so how do we fix this I got to have more cowbell baby before we get to that if you're enjoying this video and now feel obligated you need to give us money check out query GG it's our brand new interactive official react query course that we built in close collaboration with the react query team okay back to the video really what we want to do is tell react to ignore any responses that come from requests that were made in effects that are know longer relevant in order to do that we need a way to know if an effect is the latest one if not then we should ignore the response and not set Pokémon inside of it to do that we can leverage closures along with use effects cleanup function whenever the effect runs let's make a variable called ignore and set it to false then whenever the effects cleanup function runs which will only happen when another request has been made we'll set ignore to true now all we have to do before we call set Pokémon or set erir is to check if ignore is true if it is we'll just do nothing now regardless of how many times ID changes will ignore every response that isn't in the most recent effect confusing yes welcome to use effect hell so at this point we're finished right well not quite if you were to make a PR with this code at work more than likely someone would ask you to abstract all the logic for handling the fetch request into a custom hook in doing so you'd probably end up with something like this I still remember how proud I was when I first made the abstraction that is until I started using it as is this hook doesn't address another fundamental problem of using State and effects for data fetching data duplication by default the fetch data is only ever local to the component that fetched it that's how react works every component will have its own instance of the state and every component has to show a loading indicator to the user while it gets it even worse it's possible that while fetching to the same endpoint one request could fail while the other succeeds or one fetch could lead to data that is different than a subsequent request all the predictability that react offers just went out the window now if you're an experienced reactive you might be thinking that if the problem is that we're fetching the same data multiple times can't we just move that state up to the nearest parent component and pass it down via props or better put the fetch data on context so that it's available to any component that needs it sure and if we did that we'd probably end up with something like this well it works but this is the exact type of code that future U will hate current U for besides all of the context mess the biggest change that we've made is to the shape of our state because our state now needs to be able to store the data loading in error States for multiple URLs we've had to make it an object where the URL itself is the key now every time we call use Query with the URL it'll read from the existing state if it exists or fetch if it doesn't with that we've now just introduced a small in-memory cache and predictability has been restored unfortunately we've traded our predictability problem for an optimization problem as you might know react context isn't a tool that's particularly good at Distributing Dynamic data throughout an application since it lacks a fundamental trait of State managers being able to subscribe to pieces of your state as is any component that calls use Query will be subscribe to the whole query context and therefore we'll rerender whenever anything changes even if the change isn't related to the URL it cares about also if two components call use Query with the same URL at the same time unless we can figure out how to DD those requests our app will still make two requests since use effect is still called once per component oh and since we've introduced a cache we also need to introduce a way to invalidate it and as you may know cach invalidation is hard what started out as a simple innocent pattern for fetching data in a react application has become a c of complexity and unfortunately there's not just one thing to blame at this point 1 2 and three should be obvious so let's dive into number four synchronous state is the state that we're typically used to when working in the browser it's our state which is why it's often called client State we can rely on it to be instantly available when we need it and no one else can manipulate it so it's always up to date all these traits make client State easy to work with since it's predictable They isn't much that can go wrong if we're the only ones who can update it asynchronous State on the other hand is state that is not up ours we have to get it from somewhere else usually a server which is why it's often called server State server State persists usually in a database which means it's not instantly available this makes managing it particularly over time tricky though it's far too common it's problematic to treat these two kinds of State as equal to manage client state in a react app we have lots of options but what are our options for managing server state in a react app historically there weren't many that is until react query came along ironically you may have heard that react query is the piece for data fetching in react that couldn't be further from the truth in fact react query is not a data fetching library and that's a good thing because it should be clear by now that data fetching itself is not the hard part it's managing that data over time that is and while react query works with data fetching a better way to describe it is as an async State manager that is also acutely aware of the needs of server state in fact react query doesn't even fetch any data for you you provided a promise and react query will then take the data that that promise resolves with and make it available wherever you need it throughout your entire application from there it can handle all of the Dirty Work that you're either unaware of or you shouldn't be thinking about in the first place and the best part about it you can stop trying to figure out how use effect works which is why it solves the 5:00 rule if you enjoyed this video check out query G it's our brand new interactive official react query course that we built in close collaboration with the react query team
Info
Channel: uidotdev
Views: 93,247
Rating: undefined out of 5
Keywords:
Id: OrliU0e09io
Channel Id: undefined
Length: 8min 55sec (535 seconds)
Published: Wed May 22 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.