React Hooks useEffect Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
so we're gonna be taking a look at the use effect hook this one is very useful a lot of situations but it can be kind of tricky to get used to so we're gonna start off with a basic example and our worker way up in complexity so in our application here I'm going to say use state or I mean use effect and I'm going to pass a function inside of it and let's go ahead and import it up here so the basic usage of use effect is every time this component re-renders or is rendered this function will get called so we can see that if we had a console log here and say it render and now if we go over to our code you can see it's rendered once and as I type in this it's gonna render a bunch tyvan this it's gonna render even more now everything on top of this is basically ways to get this to render less and to clean up after a render has happened so if we want stuff to be called less and by I don't mean render less I mean for this function to be called less so for example what if I don't want this to be called on every render I only wanted to be called whenever I change the password we can do it like so we can say comma and then pass a array here and we can say values stop password so now whenever I change the password this render console.log is gonna fire off so here initially it's gonna fire off as well so whenever I make a change see your render changes but if I change the email this does not change so what did I just do well the second parameter here is called the dependency array that you can pass in and so here you can pass in all the values that your effect depends on and so these values whenever they change the effect fires off again and so that's the gist of it and we can put more than one if we want to in this case we have only two values but we can add another one here let's do first name first name first name values dot first name anger that a save and I can say values dot password and values email so now my effect depends on the email and the password but not the first name and I need placeholders so placeholder first name alright so we see it we see the functions getting called functions getting called functions now not getting called now the thing to note about this is this is doing a shallow comparison of the values and whenever the values change this is going to be recalled now by shallow comparison I mean if we were to put something like this object here the object is going to change on every single render the reference anyway or new objects going to be created so this gonna be called every single time in a future video we're going to cover how we can avoid such problems like this and I'm also gonna link to a video that I did about problems you may occur with use effect with closures it's more of an advanced topic that you may want to hit later on and also a great article by Dan about use effect all right so that's that the next thing to note about use effect is you can kind of replace component did amount and component will unmount with this so if we don't pass in any values to use effect here we can now have this console.log once when it mounts and that's it so doing renders not going to recall that function there and I can do a cleanup function which means we return that function from the inside of the function here and this is the called the cleanup function inside here we can add all our cleanup logic and this is going to unmount we can't really see this because it's gonna like happen like when the component disappears but if I were to create say another component here called hello GS and in this component if we toggled it if we showed it and then didn't show it we're gonna see it unmount and remount each time all right so let's copy this over export Const hello and we're I said do hello and we can just say react out use effect and here I'm going to say hello we're gonna say show hello set hello set show hello and we're gonna say use state and by default we will show it so here I'm gonna wrap this and conditionally renderer hello so show hello and then we're gonna toggle it on and off and we could negate it so now we can see that this has rendered and if I were to toggle it and it disappears you'll notice the unmount is called pull it on you can see it render and unmount again so we can see the component mounting and unmounting and those two console logs go off and we could see that happening now the cool thing about this is it doesn't just have to be when when it mounts unmount so what do I mean by that well if we go back to our example over there you can ignore hello again by the way if you don't know how to comment out blocks like I'm doing this might be hard to follow so command and then slash is how you do that probably control slash on Windows so if we go back to our use effect here let's say I want this to fire off whenever values dot email changes well whenever values are the email changes or we get it's gonna clean up it's gonna call this clean up function alright so we render I press a you see it's going to unmount we're not really unmounting we're just cleaning up the old value and then we have a new value here so that's pretty cool so that's pretty powerful that we can do that not just on mount and unmount we can do it whenever the dependencies change we can clean up anything we need to with the old stuff okay so these are kind of some basic examples and the basic fundamentals now I thought it'd be good to show you some use cases of this and regular apps so the first one I wanted to go over was with events so for example I may want to add event listener so we're gonna do mouse move and this is a nice one because when this mounts I want to start listening to the mouse and basically what I want to do is just display the current location of the mouse so I'm gonna say Const onmousemove and just to start I'm gonna console.log the event here and so I can pass in onmousemove and then I want to clean up this function when I'm done I can say window dot remove event listener mouse move on mouse move so it's pretty nice that we can use this use effect here and we can have this when it first mounts add it and when unmount clean it up by removing this another thing I haven't mentioned yet but I guess I'll mention it after we show this real quick so we can see as I move my mouse around you can see all these console logs of the values updating so effects are a great place to add event listeners and remove them and I don't even thinking you worry about showing the value on the screen this gives you the gist of it but what I wanted to show you was you can have more than one use effect on your component and they fire off in order all right so this is going to be mount one and then mount two and again you can have as many use of X as you want could see one to the fire one and after the other all right so the next one that I wanted to do is to fetch from an API so the API manifest from is the numbers API so I'm going to copy this URL so here we just pass in a number and this is going to give us access to a fact about that number so we're gonna create a custom hook for this I'm gonna call it the use fetch hook I'm gonna say export kant's use fetch and what this is going to take is a URL so I'm actually just going to paste this over here and I'm gonna get rid of some of the stuff we don't really need these anymore so the first thing that we want to do is we want to whenever this URL changes you want to fetch some data so we're gonna say use effect dang it we don't get Auto completion JavaScript for this that's sad alright use effect so I'm gonna add the URL as a dependency so this function is going to be called whenever the URL changes so here is where I'm gonna call fetch and I'm going to pass in the URL now this is going to usually if I was writing this I would make this asynchronous but BAM we're already getting an es Lent warning here it tells us that you need to return it just telling you it's not exhaustive I'm surprised the sealant warnings coming up and probably it shows a good example here it says a wait there anyway the point where I was trying to make here is you can't put a sink right here in the function and use a weight it doesn't like it so we're not going to do it like that we're just gonna call fetch and we can do dot then we could also have a function in here that we make asynchronous and then it can call like that so it's up to you you have those two choices of how you want to do it I'm just gonna do dot dot then syntax all right so we're gonna fetch from the URL and I'm going to say X dot now usually I would say X dot JSON but this particularly API is dot text so dot text and we're gonna say dot then and why don't we just console.log why so we see that the value is actually is what it is and so I'm just gonna call our look real quick so we're gonna say Const and doesn't return anything yet so we're just gonna say use fetch I'm gonna pass in our URL dang it there we go so here we can see our fact getting logged logged out here nice so let's make this more useful so I want this to basically a return to me the data and a true or false whether the data is loading whether there's anything in the data so how can we do that well we can combine this with you state to store some information so this is where you're gonna see we can kind of use multiple hooks here in our custom hook so I'm going to say set I don't know what I want to call this local call it's set data so it's gonna have data inside of here which is gonna be null by default and loading which is going to be false and we're gonna return I guess maybe we want this to be true by default and we're gonna return data this is kind of bad naming convention because data data here maybe I should call this state and we call it set state all right so here we want to say set state the data is equal to Y and loading is equal to false and then at the very start here I want to say set state data is null and loading is true so at the beginning we're gonna set loading to true and then we're gonna fetch the result when it comes in we're gonna say passing the data and loading is false so now here I can display this I can say just do it at the top you could say if we're loading we're gonna say dot that thought otherwise we're gonna display the data in this case it's going to be a string and here we can see that it's playing nicely there and now the next thing they want to do is I want this URL to change whenever I data to change whenever this URL changes so what I can do is I can add a little counter so we can say count set count good start at 0 and we can say div count is equal to count you can say increment and so now we're going to get a new fact every time I increment the counter so we can use the updater function here for our set counts and then this is what's going to change so now here is going to be the current count all right so zero is the atomic number we increment we get a 1 and we can see it populate here now I think what's happening is you saw though there's like a little bit of a jitter I think it's cuz we're displaying loading so maybe we want to say if there's data there's not data display loading otherwise that get maybe a little smoother no oh you know is it it resets the data every time right here so maybe we can get it this even smoother we can say state data so if we currently have data we can pass it in there all right so now we have a little bit smoother of transition but there we go notice how every time I increment this looks like bad gateway 10 looks like we hit a problem the API maybe we're making too many requests but either way we've made 10 requests every time we increment the counter is going to update the state here and it's passing that value to our use fetch which is updating these values so we're starting to see where this can be kind of fun and kind of useful at this now a few things I wanted to note about this use fetch first let's say I didn't include this URL then this would not you know be called every time the URL changes but you'll notice we have this nice little warning from yes lint for us the exhaustive dependencies because it sees that we're using the URL here but we didn't include it here so you may notice that you're gonna be getting that and that's a nice little reminder to add those in here the other thing is you notice how I'm using set state here I should probably add set state to the dependencies so yes you can add dependencies functions as dependencies and you probably should be and again that's where you have to be careful the function is changing every time the other thing to know is you can infinitely recur if will infinitely just call each other is if you call set state here and this triggers this to change so you can just have it infinitely call at each other and the fact keeps game calling so you have to be very careful about that as well so make sure your dependencies are not changing based on what the user fact call is at least not over and over alright so that is the use fetch the next thing that I wanted to go over last thing is a saving the state so I found a hook very nice to do this is for example if I want to persist this to say local storage so I can make a user facto here and so let's say I want to persist the value of count so here I can say I want this function to be called that every time the count changes and I can say a local storage dot set item dang it Mary a local storage and here I can say key I'm just gonna call it count and I'm gonna say json.stringify the count in case I ever want to change the count to something else beside the number later for some reason and yeah it's as easy as that so now every time the count changes it's going to set the count in local storage and now I can change the initial value of the count here by saying local storage get item count and we can do a json dot parse and again we just have a single value of count but this algorithm would work for say objects and arrays as well since we're using parse and string if I now I don't want json.parse and local storage dot get item to be called on every single render so this is a good opportunity for us to use the initializer function of you state alright so let's see this in action and see if this works so we're going to refresh here I'm going to increment this to three and we do a refresh and you notice the value of three is there so again every time I increment here it is updating the count in local storage and then when we reset or refresh is reading that value with this initializer function here so there you go that is kind of an introduction to use effect in some of the things that you can do with it that are pretty useful as you can see it has a little bit more flexibility than what you had with the class components it's kind of a new way to think about calling your data and combining these things together and we can do all kinds of chained to logic together and we can multiple use effects because right now we have this use of fetch or use fetch which has to use affect in it and then we have this other use effect at the bottom here we could also be say for example caching data that we're getting from use fetch if we want to and do all kinds of stuff you
Info
Channel: Ben Awad
Views: 136,209
Rating: undefined out of 5
Keywords: useEffect, useEffect Tutorial, React Hooks useEffect, Hooks useEffect, useEffect hook, React Hooks useEffect Tutorial, react hooks, react
Id: j1ZRyw7OtZs
Channel Id: undefined
Length: 20min 15sec (1215 seconds)
Published: Sun Jun 23 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.