Learn React #9: UseEffect & UseEffect with API Requests

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone in today's video we are going to learn all about the react use effect hook now the react use effect hooked is one of the most important things to know in react and for this video if you aren't familiar with the react life cycle of a component you should check out my last video because it's important to know how the life cycle of a component works before we look at the use effect hook which is why i made that video first we are also going to look at how to make axios requests within the use effect hook in order to get data from apis in your application and this is going to be something super important for the next couple videos where we actually make a little project with everything that we have learned so far in this react course now if you are not subscribed to the channel please hit the subscribe button leave a comment if you find value in this video i read every single comment and i can't tell you how much it helps with the youtube algorithm but let's jump straight into it so before the react components were all functional they used to be class based components and when they had class-based components they had three main lifecycle components that you would use throughout your components one was called the component did mount one was called the component date update and one was called the component will unmount and as you can imagine the three different things a component can do the three main life cycles is it will first mount it will first update and then it will unmount after you choose to not show the component anymore and as you can see each single one of these and let me zoom in a bit so you can see it easier every single one of these uh update functions was pretty much made to run on each of those lifecycle methods so as soon as your component mounted you would run a component in mount as soon as your component updated no matter how many times it updated the component did update would run and finally when your component was about to be unmounted and no longer shown on the application it would run the component will unmount function now the use effect can act as all three of these functions and you can have multiple use effects so you can decide how you want each one of those use effects to run now i have a little example set up and it's the same example from the last video and essentially what we have here is a very simple application to illustrate how you use effect works so we have an application and then we have a counter component and this button will control whether or not the counter component is rendered in or not so every time i click this counter component the counter will render in and it will go through a component did mount when i click increment the counter it will go through a component did update and when i click hide it will go through a component will unmount now let's look at the use effect and see how to set every single one of these situations up so the first thing about the use effect is you have to go ahead and import it from react note that it is not the default import just like react is so you have to wrap it around your squiggly braces just like you would with the use state hook now as you can see here i have the most basic form essentially the use effect takes two parameters number one is a function and number two is an array now the first thing we're going to focus on is this function so you can see here it's just a regular arrow function that doesn't take any parameters unless you wanted to which is a more complex example but for now let's just focus on this this specific use effect will act as a component did mount i can go ahead and console log the use effect brand and if i were to go ahead and save that and refresh our application and open up console you can see here when i open the counter the use effect will run when i increment the counter these effect will not run and when i hide the counter the use effect will not run again this is because this specific use effect will act as a component did mount and the reason for that is the second parameter that you see here in the use effect which is the array will tell you when the use effect should run if you simply pass in an empty array that tells the use effect you only want it to run when the first render is and after that because the array is empty it will not re-run and it will not be dependent on anything else happening now let's make the exact same use effect but instead of um let's and let's console log this out because we already know what it does let's just console the whole thing out and instead of just leaving nothing in the array for this second use effect let's go ahead and add our count variable from our counter into here now if i were to go ahead and refresh the application if i click show counter you will see it still runs on component did mount but now if i were to increment the count you will see that it runs every other time as well and this is an equivalent to a component did update and note that the use effect will always run on component mount no matter what whether or not you have it as a componented update or a component did mount and let's uh or i think for the did mount it's actually called let's see um yeah did mount did update and will unmount so um this one will act as a componented update because we are passing in a variable that our use effect depends on and it will only recall this use effect if the variable and you can have multiple variables in the array by the way if the variables in this array update for example if i were to have a count two so let's say oops count two and set count two equals use state and we'll set this one to zero as well so now we have a second count variable and if i were to for example like let's make a second button that says like increment count two and i made the setter for count two you'll see here if i open it up and i increment count two the use effect will not run because the only thing in the array is count but if i were to also add count two and let's go ahead and refresh this and open it again you will see if i increment count one the original count it will update and if i were to increment count two oops it will also update um i'm not too sure why it stopped updating here um i think that might just be a bug oh it is because i i've been setting set count to count plus one when it should be count two plus one there we go so now if we were to try that whole thing again i go ahead and show it i increment the count and i increment count two and you will see the reason it didn't update with regular count is because we were setting it to the same value and therefore the value didn't update and therefore the use effect didn't run so that's actually a pretty interesting use case to know about now the final example of um using a use effect we are going to use the use effect with a component will unmount so if we come over here we can get rid of all this and leave in an empty array and now we can make a return function be an empty arrow function and in here we can console the log and say we the return is being ran and note in the official documentation this is known as the cleanup function so if you were to put a return and let's see if i can quickly find an example in here so i don't know why they don't have really good examples but for example here you can see in this use effect they have a return and this will specifically run when the component is unmounting and only when it is unmounting so you can see here i'll go ahead and refresh and i show it it'll still run the first time anything that's inside the use effect other than the return if there is an empty array here will still run the first time but if i were to you know go ahead and update all these counts and stuff like that you'll see the use effect is not running because we have an empty array passed in here and now if i were to hide the counter which would unrender it you will see that it first runs the return function so if i click it it'll say the return is being ran and that is known as a component will unmount now you might be wondering okay so let's say we take an example like this a simple example and we just don't pass in an array at all what is going to happen well you're going to see what happens is if i were to go ahead and refresh this now it will literally update no matter what on everything so this is sort of the equivalent of passing in every single possible thing in your component into that array which is pretty dangerous because that means no matter what happens to the components you know in most components you're not just going to have two state variables you might have you know redux things you might have props coming in every time any one of those things updates you're going to have this use effect running so it's very important when you have a use effect unless you want it to update literally no matter what updates you want to add that array parameter and you want to put only the things you actually want it to run on update work so for example the count or for example count two which is really important so you can see here those are the three main ways to get the life cycle methods inside of usefx and of course you can do things like for example combine them so let's so for example if i were to make this dependent on count and we will see that it is simply just working as we know as a component will update every time i click it it'll give us this but now let's try adding a return here and see what happens so you can see here in this return in this cleanup function all i'm doing is i'm pretty much saying i want to console.log this every time we are quote returning now you might think that this will only run when the component unmounts however now that we have added something to the array in our use effect it will no longer run as a component will unmount and instead it will sort of run like a component will unmount specifically for every time any variable inside of our array changes so i'm going to open that counter and now keep a close eye on what the count is if we increment the count to one you will see here it will get the message that the count uh that first we will get the message that the we are in the cleanup and the count is zero and then we get the message that the count has updated and essentially when you put a variable here this cleanup method will now run for that variable changing so the exact events of what happened the exact order of events was we updated we reloaded our application and we showed the counter and we are now in this state where we have already run this console statement saying the count has updated and right now the count is currently zero when we now change the count before it fully changes we are going to run this cleanup function and this cleanup function is going to happen right before the count updates and that's why when you console log it it will say that the count is zero and not one and why after that this use effect will rerun saying that the count is updated and to make this even a bit more obvious we can go ahead and add the count variable in this first in this first use effect so we can clearly see uh what it is so we show the counter and it says the count is updated to zero we are in the first run of it now when i click increment count the cleanup will run and that's why it'll say the count is zero and then the use effect will rerun because the count has changed and we can see here the count is now updated to one and if i were to click increment the count again you will see that the cleanup runs first and it is set it'll say that the count is one and then the count will update to two so that cleanup will now not um will not be known as a quote component will unmount anymore but it will be tied to the variable inside of the array so that's one of the complex ways that you can combine a cleanup function with a standard you know use effect made to update um to run on update now let's talk about how we can make an api request using the use effect hook and in production level applications you should all know that a lot of the times you're not going to be making api level requests at the use effect level a lot of the times you're going to have something like a redux store and your redux store is going to hook up to redux saga or something that's going to make the api request for you which we'll go over in future videos but a lot of people like using use effects to make api requests and it's something that is good for small projects so let's go ahead and do that i have found a really nice fake um api over here called jsonplaceholder dot i'll link this in the description in case you can't read that but essentially it has a bunch of different fake apis that you can hit that just return some basic json data and the one we're going to look at is their to-do's endpoint and you can see when you hit the to-do's endpoint you just get a bunch of um to do so for example each to-do will have a user id that i guess is assigned to that to do an id the title of that to do and whether or not it is completed and you can see there's like quite a lot if we scroll all the way down there's 200 to news um so we're going to hit this end point and get this json and just simply display it and in order to do that i've simply made a very basic function over here and we're going to use the component did mount hook now the reason we want to use the component did mount in our use effect as opposed to anything else is because we only want to load this data one time and we don't want to be making you know multiple different requests um uh you to get the exact same data every single time a variable in our component updates so what we're gonna do first is we're gonna install a dependency called axios which is a nice little library that sort of wraps around api calls and ajax calls and i like using axios a lot and i have a very brief example of how to use it in case anyone is sort of new to it essentially all we are going to do and you can even see this example that has react in it they're using it in a componented mount but essentially all you do is you import it and then you type axios.get you type in the endpoint and then you just have a dot then which allows you to do whatever you want with that data so essentially what we are going to do is i have a state variable here and i'll close the um this over here now i have a state variable called to do's which we are going to store all the to do's in and what we're going to do is we're just going to have a compo a use effect here and we're gonna go ahead and import axios oops okay we're gonna go ahead and import axios and we are adding an empty array here because we want it to only run one time when the component mounts and what we're going to do is essentially we're going to take that call and add our own url in there so let's go ahead and delete this we're going to say axios.get oh i spelt it wrong up here okay we're going to take axios.get and we can go ahead um and replace the url so let's get the url of this oops and this code sandbox will be in the description as well so you can straight up come to all this code and play around with it you can fork it onto your own account play around with it so and then what we're gonna do in the then with the response data we're to say you know const to do's is going to be equal to the response data and then what we're going to do is we're just going to set to do's we should call this to deuce to the to do's um you know response or let's call it like yeah response to dues so this is the to-do's that we're getting from our endpoint and we're gonna set our state variable to do's equal to that and just to walk you through the flow of exactly what is happening let's take one more last look at the code what is happening is our to-do list is being rendered and as soon as it gets rendered this use effect will run and when the use effect runs it will make an axio get request to this api or this endpoint and then after the request is done it will it has a callback function with a variable called res which stands for response and all we are doing is setting essentially the to do's in our state variable equal to whatever the response data is from that endpoint and now this to-do's um variable state variable should have all 200 to do's in there so what we can do if we wanted to for example display all of it is we could just map through it so the first thing we're going to do is we're going to make a conditional to make sure that we are only mapping through it is if it is defined because in the initial state of our component we are sending it to undefined before this use effect gets a chance to run with the api request because this actually takes some time so the next thing we're just going to simply do a simple map through it so we're going to do dot map and let's say for example let's just pull out let's say like the user id the user id and let's say like uh what else do they have the title um the title equals to do and let's just return something really simple like you know like an h5 that says the title of the to do and then an h6 that says like assign to user and then the user id that the to-do is uh assigned to okay and let's wrap some fragments around it so we have a top level and let's go ahead and refresh that and you can see here all right it's we're gonna get that key warning so we can just go ahead and like let's turn this into a div and let's say the key is equal to the and let's get the actual id from it um if you've watched our mapping videos you'll know why we have to assign a key but let's go ahead and now refresh this and here we go now react stops yelling at us so and let's make this to-do list in h1 just so it looks a tiny bit easier to understand cool so now you can see what is happening here is we have our to-do list and for every single to-do list for every single to do in that list we essentially are showing the title and which user it is assigned to obviously you can make this look a lot better but the purpose of this video isn't for aesthetics we're just learning how to use the use effect with an api request and that is essentially uh how that works and if we wanted to even look a bit further we console.log the to do's variable and you'll see when it first rendered you'll get probably two undefined and then two times where it um renders uh where the variables are actually things all right let's go ahead and refresh that so you'll see here it'll you know the first couple of times that this component renders you'll get undefined but then it finally makes the api request and updates the variable and then you see the variable is updated to all 200 of these to do's in our response that we get back but that is pretty much it and if you found value in this video um i know it might be a bit complex and in the next couple of videos we're gonna make some examples combining everything we learned together but hopefully if you found value please consider subscribing or leaving a comment i can't tell you how much it helps with the youtube algorithm liking helps as well and i try to read every single comment that you guys leave so thank you so much for watching hope you're all staying safe and i'll see you guys in the next video
Info
Channel: Anthony Sistilli
Views: 45,252
Rating: undefined out of 5
Keywords: React, Reactjs, ReactJS UseEffect, React useEffect, React useEffect tutorial, reactjs for beginners, reactjs useeffect fetch data, reactjs useeffect not working, reactjs useeffect infinite loop, react useeffect api call, react useeffect hook tutorial, react useeffect hook, react useeffect async, react useeffect usestate, react useeffect cleanup, react useeffect explained, react useeffect axios, reactjs hooks, react useeffect dependencies, react useeffect fetch data, react hooks
Id: 3Wb9l18KoxI
Channel Id: undefined
Length: 20min 16sec (1216 seconds)
Published: Sat Oct 17 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.