React Query - Complete Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up guys thirst cousin here today we're looking at react query and I'm going to teach you everything there is to know about it bonus points for you if you watch until the end of the video you just might become a senior developer let's go cool so react query let's talk about it actually I maybe should call it time stack query because this is also available for other Frameworks like solid View and svelte but essentially react query is a data fetching library that makes it super super simple to fetch your data in react you're gonna see that with literally just one hook we can achieve an insane amount of functionality so to get started you're going to want to have an app already set up and you're going to want to install react query you can look at the documentation as to how to and then the first thing that you need to do is you need to create a query client and then wrap your entire application with a query client provider that you get from react query so let's do exactly that first we're going to import the query client from react query so import query client from your query and also we're going to import the provider writer so query client provider and then we're going to create our client that's going to be like so chat GPT is going to be super useful and do it for me essentially you're creating a const query client and then you're assigning it to a new query client from your query and then we have to wrap our entire app with the query client provider so I'm going to copy this come here to this and then just put this at the end so we wrap our demo and then we need to provide the query client to the actual context so client equals query client essentially what this is going to do is it's going to allow us to use this query client anywhere in our application through this context which by the way if you don't know how context Works in react I do have a whole tutorial on it make sure to check it out it's really useful and also it's going to allow us to have access to all of the hooks that react query provides us to do all of its magic and with that we have everything that we need to now use react query in our application now I have here this file it's called API but it's actually not an API it's just mocking the API it essentially has a static list of to-do's each to do has an ID property a title and a completed Boolean and then we have two functions one to fetch the to-do's and one to add a to do we're going to use this file to mock our API and use it with react query the code for application looks exactly like this it's super super simple right it just has this text here that says react query tutorial and this is how it looks it's just literally that react query tutorial there's no data being fetched so now we need to fix this because we want to show our to-do's here using react query so the way that we're going to do that is we're going to use a hook called use Query which is the main hook that you use whenever you want to create a query with react query so we're going to do import use Query from your query and then make some space here and then the Syntax for this is const query equals use Query like so now use Query takes in some parameters and the easiest way to pass them is just to pass an object here as the first and only parameter and you can pass all of the properties inside we're only going to be concerned with two properties that is the query function and the query key so the query function is going to be this one query FN and that's going to be the function that we want this query to have in our case we want this to fetch our to-do's so we're going to pass an arrow function that Imports our fetch to Do's like so then we want to provide a query key so we'll do query key and this is really important we're going to talk about this in just a second because react query will use this query key as a form of identification for the query for it to do all of its caching magic and everything else that it does for now we're not worried too much about that since this is the to-do's query we're going to fetch some to-do's I'm going to give this to-do's as a query key and with this if I just make some space here we have all of the things that we need to do a complete query of our to-do's with react query you can see that it's super super simple right that's the beauty of react query now one thing that I want to do that I suggest you also do is I want to destructure this query variable and only access the properties that I actually need in my component so I'm just going to destructure this and then the first thing that I will get is something called Data this data is going to hold our actual data what is being returned by this fetch function in our case it's going to be our to-do's and actually I'm going to Alias this as to Do's just because it's going to make it easier to use within our code and then the other thing I want to get is a Boolean called is loading and this will be able to indicate to us when this query is loading so we can use this to show the user something as the query is being fetched then I'm going to come here and then do if is loading I want to return a div that something is loading and then at the bottom here we want to remove this thing that says the tutorial and then I want to map over my to-do's so I'll do to Do's question mark.map the reason why we have question mark is because initially before this is being run our to-do's are going to be undefined we're not going to have any to-do's before we fetch them so we need to handle this case in our code in our case when that happens we have this if check here that is going to show something to the user so we don't really need to do anything if our to-do's aren't defined here then we'll do that map and then to do and that is going to return I actually have a component already built for this that's going to be a return to do card and then we're going to pass the ID as the key and the to do as the to do and then I'm going to save this and that's it so now with this if I actually go back to my application you're going to see that we have or to Do's directly listed on the screen also if I refresh you're going to see that we have loading here right that takes a second because our API if you haven't seen is hard coded to wait for a second to simulate actually fetching something from the API so this looks really really cool with just a few lines of code now that we have our query successfully working the next step for us to do is to look at mutations let's enable our application to add a to-do so mutations in react query thankfully they're really really simple and they're actually super similar to how you do a query it's actually just another hook that is called use mutation which is going to be used to make a mutation and then the Syntax for it is const mutation equals use mutation and then just like so now just like use Query you can also pass this an object to pass all of the properties that it needs and then instead of a query function you're going to do a mutation function and that is going to be the function that we want to run as this mutation and in our case it's going to be add add to do which we can import as well as our fetch to do's and honestly that's like really it this is all the code that we need to have a successful mutation now just like I destructured this query here to get all of our properties I'm going to do the same thing with our mutation so I'm going to come here destruction this and then to actually get access to the mutation function that you can then use in a button or any other function we can do two things we can do either mutate or mutate async now these two are exactly identical they do the same thing the only difference is that mutate async is asynchronous which means that you can await its response whichever one you choose honestly doesn't really matter it's a matter of preference at this point I generally like to use the async version just because I like more the way how the code looks when you await something so I'll do that I'll get rid of mutate and I'll use mutated async and then I also want to Alias this as add to do mutation just because it's going to make it a little bit more explanatory when we're actually using it in the code then what we're missing is some UI to be able to add a to-do so I'm going to create here a new state variable called const title and then set title and that's going to be use State that's going to be instantiated to an empty string and then we need to actually here in the UI create a div and then inside we're going to put an input of type text and then on change it's going to take the event and it's going to set the title to e.target.value and then it's going to take value as the title that's going to be our input and then we also want a button that's going to say add to do and in here we're going to come and use our to do mutation so on click and now what do we put for our mutation right well since first of all this is mutate async we're going to have to put an asynchronous function so I'll do async here if I can type my God here and then open an arrow function and here's where we get to put the code of our mutation so what I want to do is first create a try catch block so try and then I'm going to do a weight add mutation right and then I'm just going to do catch error and then we're just going to console log the error if anything now I went a little bit fast because Chad GPT copilot actually filled this out for me but essentially what this function is going to do is it's going to be an asynchronous function which means that we can use the await keyword to await the function then we're going to await our to-do mutation which by the way is typed right if I omitted this title it would tell me that there's an error that we're missing some variables because react query is smart enough to know that in our function definition here at to do we take it we have it taken a to do property which is only going to have the title property of R to do so if we don't provide it it's going to complain so to fix it again we just have to provide title like so and then it's going to not complain anymore and then the last thing that this function does is it sets the title to an empty string to essentially reset the stage so that we can easily add a to-do afterwards and now we can go to our app we can see our new input and our button to add it to do and we can start adding or to do so what I'm going to do is subscribe to cause then Solutions because did you know that over 30 percent of you watching are not subscribed which is honestly unfortunate because you're getting a ton of value from these tutorials so if you're not subscribed I would highly encourage you to do so the button is right below so that's going to be our new to do we're going to add it and we're going to see that our input is going to get cleared which indicates to us that this was successful but our to do is not showing up in the list what's happening well for that we have to go back to our fetch to do query and look at this query key here remember how I said that this query key was super important that this was what react query would use to handle all of its magic which the magic is handling all of your API requests for you and giving you all of these properties but also the caching react query uses caching via this query key it uses this query key to create a cache for this query which the cache is basically just these to do is the result of the Fetch and then it's going to show you that cache instead of fetching from from the back end over and over again now when we're making this mutation here there's nothing telling react query that it needs to fetch new data that there's a new to do to be fetched right it doesn't know this mutation and this query they're not linked so what we have to do is we have to make something to this mutation to tell react query through this query key that this to Do's should be refetched so what we can do on the mutation side is besides mutation function we can provide a function called on success and this is going to run actually I don't want it to run with all these variables but on success this is going to run whenever this mutation is successful which is what we want and then here we want to invalidate our to-do's query to make it refetch to make react query refetch the data now to do that we're going to make use of this query client which we set up here in the beginning of this video because this has some methods that allow you to invalidate queries in react query now to do that we're going to come here and we're going to use another Hook from react query it's called use Query clients we're going to do const query client equals use Query client you can import it right here maybe also make some space and this query client again is the same one that we passed through here it's accessible through this context here this one we can come here into our on success and we can do query client dot invalidate queries and here instead of to-do's we're going to put this as an array because we put this as an array essentially this code on success of this mutation will invalidate the queries by this query key to Do's which in our case is this query here so this is going to get invalidated which is going to force react query to refetch the to-do's so now if I go back to our app and I add another to do and I press add to do it's going to make it disappear and then it's going to refetch the to-do's because we've told our code that that's exactly what it should do it should invalidate the queries whenever this mutation is successful so now we've covered mutations and queries in react query now there's a few things that I just want to mention because they're going to be really useful and chances are you're going to run into them when you're applying this in your own projects the first thing is what if there's a parameter that you want to pass to your fetching function this fetch to do is if we look here fetch to Do's takes in an optional query parameter which is just getting defaulted to an empty string right what if you wanted to have an input that the user can type in and search all of your to-do's how would you do that with react query well the first thing you would do is you would maybe have another piece of State called const search and then set search and then use State as well and then we're going to clear this because I don't know what copilot did and then you would want to pass this search here right to your fetch to do is because it takes in an optional query of type string so this will match but now your query key doesn't account for the search and this is a problem because if search changes if the user types something in the input box to search their to-do's react query is not going to know that that search is different from the one before because you haven't provided this in the query key so what you need to do is every parameter that you pass to your function every parameter that your function depends on also has to go in the query key so I'm going to do a comma here do an object and then do search you want to always make sure that everything that you pass to your fetching function everything that it depends on also shows up in this query key because that represents a new state of the query right this query is not being run with this search value and so the query key has to also apply to that value and then here on success where you're invalidating the query you actually don't want to provide the search or any other parameter because you want to invalidate every single query that has to do's and you don't care about the search this is how this works this is a partial match so this is going to invalidate every single query that has to do regardless of whatever else parameters they have in their query key and this is great because react query allows you to do any sort of customization that you want with your queries and then do any sort of manipulation you want to them and everything is based off of this query key so it's really really important that you understand the query key and that you always make it unique per request and you include every single parameter another thing that's really important to know about react query is how it handles its cash because the defaults that it has are super super important so if I go back here to our root application I've added now some code I've added here this piece of State called show demo which is essentially going to control whether our demo our entire app is going to be rendered or not and this is going to make this component unmount and remount which is going to recreate every single query right that's what it's going to do I want you to pay attention as to how react query works out of the box with no configuration so in our app we now have our toggle demo button and I want you to notice what happens when I refresh the page I refresh and we see loading I want to refresh again in case you missed it we see loading now look what happens when I toggle the demo which should do the exact same thing in the component it should remount the component and the query should be fired again I'm going to toggle the demo toggle it again and you're going to see our results are here right away and there's no fetching that's because react query by default will cache your data for this request and it's going to know to Cache the data via this query key here and then it's going to show you its cache data if it has it which we did when we reloaded the page right it's loading the data for the first time it has it it's in the cache I toggle the demo I toggle it again it's showing me the cache but then this is really important react query will make a request even though it's showing you the cache it will make a request in the background and then update your to-do's without being visually obvious and you can see this if we open up our console and I refresh the page we have fetched to Do's right because I have this console log here and this fetch to Do's I have here fetch to to Do's so we're seeing this the first time right and then I toggle them on I toggle it again we have our data but fetched Deuce is being fetched again that's what react query does by default out of the box it'll show you your data if you have it cached and then it's going to make a background fetch request and update it without being obvious if you want to remove this Behavior you can do still time here where you have your query and you can put this to Infinity right this will tell react query that it should never consider its data a stale which means that the data is still valid and so if you do that react query is not going to refetch the data even in the background so I go back to our app I refresh it's going to do our first request as normal but then I toggle demo I toggle it again it's showing us the cache data but it's not making another fetch request if you want to remove the caching functionality altogether you can do cache time and then put zero this will tell via query that it should never cache the data at all and it should always make a fetch request no matter what if I go back to the app now I refresh it's going to say loading and then I toggle demo toggle it again it's going to load the data fresh again not do any caching not do any background fetches now this is important because these are the defaults that react query uses and if you don't know about them you're going to be very confused if you're using this in your app because you're not really going to understand what's going on at the same time react query is beautiful because it gives you the option to completely customize all of these options per query or like I've done here I've actually added some code here you can set some defaults that apply to every single query and there are a ton of other things you can do like you can do refetch interval you can do refetch on Mount there's a ton of other configuration you're welcome to go and look in the documentation because this is a very extensive library and chances are the thing that you're trying to do this is going to be able to do it and there you go that was react query this is a very important tool Library whatever you want to call it that is really useful if you need to manually do your API requests I know that that's not always the case with like next.js or server components right we're moving away from this but if you're working in react native or if you're doing your own create react app or create Veet app this is really really useful and also I'm sure that react query is going to find its place eventually once server components are fully mature if you enjoyed this video as always you can leave a like you can subscribe it really does help me out a lot it shows me that you enjoy my content if you haven't joined the Discord it's the first link in the description again I would strongly recommend that you do so it is the best resource for learning react if you're looking to learn react which I can only assume you are if you're watching this video right so again first thing in the description with that being said my name has been nurse cousin this is causing Solutions it's been an absolute pleasure and I will see you all in the next one ciao
Info
Channel: Cosden Solutions
Views: 73,988
Rating: undefined out of 5
Keywords: react tutorial, react crash course, react developer, learn react, react hook, react hooks, react hooks tutorial, useeffect hook, useeffect tutorial, programming tutorial, react hooks explained, computer science, tutorial for beginners, react component, learn programming, web development, frontend development, coding for beginners, simple code, easy programming, react query, react-query, tanstack query, transtack, transtack-query
Id: 8K1N3fE-cDs
Channel Id: undefined
Length: 18min 56sec (1136 seconds)
Published: Wed Jul 26 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.