React Query Is (Still) Essential - My Favorite React Library

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
data fetching is hard it involves all the worst parts of JavaScript validation asynchronous behaviors and error management as such getting data fetching right is really important and I've seen a lot of people do it in a lot of different ways that let's be frank vary a ton in quality one of the pieces I've seen the most is react query and there's some really good reasons for that whenever react query comes up I always see the same response why would I use that when I could just fetch in a use effect and throw it in state well you can but the reality is isn't that simple so I want to take some time to dive into why you actually should use something like react query and the benefits you get from having a good core data fetching solution for your applications without further Ado let's take a look at this awesome blog post by TK dodo why you want no why you need react query I want to be clear even though I'm using server components now I still agree with almost everything TK is about to say so let's break down what he's saying and why TK doo. if you're already using react query and you haven't read practical react query get on that there will be a link in the description really good stuff it's no secret that I heart react query for it simplifies the way we're interacting with a synchronous state in our react applications I know a lot of devs feel the same important piece here a synchronous State notice how the word fetching hasn't come up yet sometimes though I come across posts claiming that you don't need it to do something as simple as fetching data from a server we don't need all these extra features that react query has to offer so we don't want to add a third party Library when we can just as easily fire a fetch in a use effect to some degree I think that's a valid point react query gives you a lot of features like cash retries polling data sync pre fetching and more and about a million more actually I'll go Way Beyond the scope of this article it's totally fine if you don't need them but I still think this shouldn't stop you from using react query actually this is possibly the first point I disagree with if you're using a framework that is built in solutions for data fetching mutations you might not need react query you might not yes hopefully he dives into why you might because I obviously use these Frameworks very heavily a big nextjs user and I still find a ton of use cases for react query around other things that are asynchronous we'll dive into all that in a bit though so let's instead look at the standard Fetch and use effect example that came up on Twitter lately and dive into why it might be a good idea to use react query for these situations too Fetch and use effect con data set datas use State error set error use State use effect fetch endpoint category then Jon it then set data catch put the error there categories the input now we have theoretically everything we need to return this data think this code is fine for simple use cases where you don't need additional features let me tell you that I immediately spotted five bugs hiding in these 10 lines of code let's take a look here and see if y'all can catch any of those before we continue the first one that's jumping out at me is order of events if this fetch call hasn't responded before we change category so we change what we're fetching and then that second one comes back before the first one whichever resolves last is the state you're going to have so if we have category a initially and before it responds we go for category B category B responds immediately and then a responds after we get back the data for a even though we're asking for the data for B that's just the immediate one that comes to mind here I'm as I said there's at least four more hint is that the dependency array that's fine race condition woo guess the first one right there are reasons why the official react docs recommend using either a framework or a library like react query for data fetching while making the actual fetcher Quest could be pretty trivial making that state available predictably is certainly not the effect is set up in a way that it refetch whenever category changes which is correct however Network responses can arrive in a different order than when you send them so if you change the category from books to movies and the response for movies Ares before the response for books you end up with the wrong data in your component here we are ra if books is requested first movies are requested second this set data gets called before this one and you end up with the wrong data an inist and state the react doc say we can fix this with a cleanup function and an ignore Boolean so let's do that this is a fun one you have an ignore then you can escape if you're not supposed to ignore and then this return if you're familiar with effect and the behavior of return for a cleanup when category changes this runs category changes and then this all runs again for the new C category so if you've set ignore to true you change the category now when this responds later it effectively is tossed out what happens now is the effect cleanup runs when category changes setting the local ignore flag to True fetch response comes in after that it will not call the set State anymore awesome loading State it's not there at all you have no way to show a pending UI while the requests are happening not for the first and not for the future requests so let's add that SLE loading set is loading true finally set is loading false at the end there not too bad but again with the ignore gets a little bit more complex now empty State initializing data with an empty array seems like a good idea to avoid having to check for undefined all the time what if we fetch data for a category that has no entries yet we actually get back an empty array we have no way to distinguish between no data yet and no data at all this helps if we initialize with undefined instead data and error are not reset when the category changes that's also important if you change the category the previous data and error shouldn't still be there we should wipe those out and it even be possible to have an error for one thing and data for a different thing at the same time if you're not wiping them out at the very least in this we should be wiping the current error we should probably doing a lot more than that so here's where this is added set error undefined or in this catch set data undefined but this still isn't handling when the category changes we should have in this return set both the undefined also fires twice in strict mode it's more of an annoyance it's definely something that catches new react developers off guard if your op is wrapped in strict mode it will potentially call the effect twice y y we've complained about that enough times on the channel yeah anyways bonus error handling didn't includes in the original list of bugs because you'd have the same problem with react query fetch doesn't reject on HTP error so you'd have to check for res. and throw an error yourself yeah it's annoying this is the case with web but I get why I might make a custom fetch I do that in a lot of code bases where it throws if res is not okay fetch do then if not okay throw a new error fail to fetch otherwise we return rest Json and we have the then and catch notice how much code we now have for what was supposed to be really simple we're at 38 lines of code apparently there's a whole article about why fetch doesn't throw that might be worth making some content about in the future let me know in the comments if I should do a video All About fetch not throwing and the weirdness about errors in Fetch anyways our little we just want to fetch data how hard can it be news effect hook just became a giant mess of spaghetti code as soon as we had to consider edge cases and State Management so what's the takeaway data fetching is simple Asing State Management is not Tada very very well put this is where react query comes in because react query is not a data fetching Library it's an async State manager I've been saying this forever it's really nice that the core react query team is too because it's so important to understand the beauty of react query isn't just fetching data from a server I remember way back like way way back possibly even four years ago I was watching Jason langdorf have Tanner on to talk about react query and having my mind blown when I learned not only is react query not just for graphql stuff it's actually not just for fetch it's for anything async so if you need to async await for some I don't know AV devices like my webcam which we do a lot for our web services like pay the video call app react quer is a really good way to handle the loading case the error case and all of those things wrapping the complexity of your AV devices by just dropping the promise and use Query we'll show that off in a bit but I want to showcase the examples here first as he said when you say that you don't want it for doing something as simple as fetching data from an endpoint you're actually right even with react query you still need to write the same fetch code as before you still need it to make the state predictably available in your app as easily as possible because let's be honest I haven't written that ignore Boolean code before I use react query and likely neither of you I actually had but it was noxious and I'm so happy I don't have to anymore with react query the code above becomes this cost is loading data error equals use Query we have a query key which allows it to be uniquely cached we have a query function which is just this function nice simple to the point really clean only 11 lines handles all of the edge cases de bounces has really good caching behaviors you can call it multiple places phenomenal it's about 50% of the spaghetti coat above and just about as long as the original buggy snippet and yes this addresses all of the bugs we found automatically no race conditions to handle that you get all the loading error in all those States empty states are cleared separately whenever you change the inputs you will not get data or error from a previous category unless you opt into it and multiple fetches are efficiently D duped including those fired by strict mode so if yourself thinking that you don't want react query i' like to challenge you to try it out your next project that you'll not only wind up with code that is more resilient to edge cases but also easier to maintain and extend and once you get a taste of all the features that it brings you'll probably never look back I totally agree lot of you mentioned missing request cancellation the original I don't think it's necessarily a bug just a missing feature of course react query has you covered here as well with a straightforward change o signal you actually pass the signal from react query and it will terminate this for you your signal you get query function for it to fetch and request will be automatically aborted I didn't even know that that's dope I do want to quickly showcase using react query for something that isn't fetch here are some real code from the Ping code base you see here we're importing use Query and use Query client from react query so what are we doing with that they got a couple fun things so this is an interesting hook I built in order to invalidate the existing cach values whenever your devices change so if if you plug in a new webcam or you unplug a microphone this will invalidate all of your devices because we only know that a device changed so I invalidate all of these queries so now react query will automatically refetch the data for all of them and it will rerun the functions it has to in my case I'm using the aora web RTC provider and it doesn't have a great react binding I think it is better now but at the time it was awful so I have used query string cameras is the key it's an async function that Returns the result of Agora RTC doget cameras and now I have all of the camera devices here can also have a loading State and an error state if I don't have permissions I could throw an error here there's a lot of cool stuff I can do but you'll notice this is not fetch code this is client side specific code that is a weird asynchronous thing you'll also see this trpc do usequery the Syntax for this has changed a little bit since where before you would have to pass the endpoint as a string now it's part of the trpc proxy object but the result is still very similar in react trpc uses react query to give you a really good asynchronous flow to get this data from your endpoints so now I can use use the same syntax and the same behaviors to get things from my API endpoints and from your device it's so cool that this primitive is powerful enough that it's not just useful for data fetching it's useful for so much additional stuff and this is why it's hard for me to take people seriously when they say you don't really use react query but this is all why it's so hard for me to take people seriously when they say you don't need react query because you certainly don't need it but a lot of the problems that we have every day as web devs benefit greatly from a pattern like what react query introduces if you're not doing anything complex with asynchronous code at all yeah buddy if you're not doing anything complex with your asynchronous code then sure you probably don't need it but the amount it benefits you and the amount it simplifies the experience working in your code base for everything from data fetching to weird local acing functions is just so powerful that it's hard for me to work in a code base where I can't reach for react query when I need it hope this was helpful rant my cat clearly wants my attention so I guess I'm signing off now you want to hear more about cool data fetching stuff pin a video in the corner all about that I'll see you in the next one peace NS
Info
Channel: Theo - t3․gg
Views: 139,200
Rating: undefined out of 5
Keywords: web development, full stack, typescript, javascript, react, programming, programmer, theo, t3 stack, t3, t3.gg, t3dotgg
Id: vxkbf5QMA2g
Channel Id: undefined
Length: 11min 3sec (663 seconds)
Published: Tue Jan 23 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.