How to use React useEffect Hook Properly and Efficiently

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello world and welcome to this video of views effect that react hook the reason I made this video is because use effect is probably the most important hook there is to react it's pretty much the biggest game changer there's been to react sense react first came out it it there's a lot it can do and there's a lot of things that it does that people don't realize it does and there's some additional rule hook rules you should follow that not people don't always follow her they don't know why they should follow him so I'm hopefully gonna show you some of these gotchas and how to use the use affect properly so first I just want to get this straight out the door if you are coming from classes react classes where you would use lifecycle methods such as component did now component an update component did unmount you might want to say use effect is essentially all of those lifecycle methods and one and while that might be true in some levels it's very important you differentiate use a fat from lifecycle methods traditionally lifecycle methods what they would do is update the component based on where the component was and its life cycle so when it first updated I want it to do something when it when the props have changed I want it to do something when the component unmount I want it to do something use effect you need to think of your component as when the state or the props change how do I want this component to update how do I want this component to constantly change per those props and state so it's very important to realize that use effect needs to be always firing it's not a certain time in the components life it's whenever the props are state change this use effect is going to get fired and this is how it should update the component so it actually helps your components be more future-proof without you even realizing it so we'll get into that in a second but first let's go into this basic example of how to use effect hook so as you can see we have a you state hook count and set count setting the initial count to zero we have a button that when you click it it's going to increment the count by one and we're just playing the count here and we're also console logging it in this use effective so as you can see in the console is was fired on the initial render so if we refresh does use effect gets fired on the initial render and whenever we click it's going to get fired this is because this use effect is getting called every single time this component re-renders so this can be a problem especially if we have multiple states we don't want to use effect to be firing every single time every state is being updated so for example let's just create another state and we'll just call it set count to and this one I start at one and we create another button it says set how to count to you plus one and we'll get this - that's confusing okay alright so here's the initial state we still only get one console log because it's only fired the first time I won't cook the first one you get the console log added with the updated state and click the second one you're still getting the console log but that first state isn't changing that's because this is rendering every single time this component updates whether that's through the state for the props so in order to fix that we can add dependencies to this use effect so that's just a second argument and they use effect look so the first argument is a callback function the second argument is an array and this array is all the dependencies when this use effect should run so in this case we only want it to run when account has been updated so save it you still get that initial count and when we click it you still get the console going click the second one it's not consoling because it's only going to fire when the count changes now one of the common questions I hear or something or you know kind of doubts about this hook is do I really need to pass in all of the dependencies all the time because there is a nice lip warning that will come out right here let's see if we get it yeah says has a missing dependencies account either include it or remove it remove the dependency array so if you haven't a dependency array which you always should because you always want to be optimizing your use effect because that can cause a huge performance issue if you don't optimize your ease affect you always want to put all of the external factors within this dependency array the reason being you want to make sure that this use effect is always changing with the latest props and state and so if you're consoling something that's external such as the state you need this to run whenever that changes however there's some times when you think oh I only want this to run on the initial render so let's I'll show you an example of why that would not actually be the case and you want it to read it whenever the props change so I'm gonna go to the index file and I'm going to open up this other file called initial effect so in this example we have an items and item state with the set items and it's initializing to a single array item in here which is the label but we'll get to this he's effect in a second essentially it's just mapping all over the items and yeah mapping over and just playing the text so we have this wrapper function which is controlling the number of items which is a prop now when we initially created this component we thought okay so whenever this component Mouse I want to take the number of items and I want to create an array of objects with that number of items which is what this is doing and then put an object in that array generating this essentially so we wanted this to happen initially right so we just set this empty bracket we do get the morning but you know we don't care about that so we're just going to leave a blank because we're only expecting this prop number - coming once well now later down the line let's say we get a feature request to be able to toggle the number of item between 1 and 3 so that's what this button here is and so this button is going to toggle the number of items from 1 to 3 so you think Oh initial effects has this prop number of items initially it was just set like this but now we can set it to a state and update the state and you'd think that when we click set to 3 it would update the 3 but it's not the reason is because this number of items is not included in the dependencies so it's never going to update and while you might think when you're first creating the component this prop will never change or even if it does I don't care you 99 percent in time you want to always update when the prop updates if that property included and the seed effect so this is future proof in your code this dependency will exhaustive dependency as a he is level you should always follow it you'll definitely have co-workers question it all the time especially people who are new if you always need to include it even though I only wanted to run once you want it to always run because you don't know in the future what changes may come externally but you always want to make sure this component can handle any external changes so we're gonna say number of items in here and that will teach boot fit so let's refresh it so start talking at one but when you click the button accept it to three so that's one of the reasons why you always want to have your dependencies in this raft now let's say there is a reason why you only want it to run once there are rare cases like this keep in mind this should be a last resort but there are certain things like for example tracking you only want this attract the first time the customer has seen this component or what have you so let's get rid of this well let's keep this for now let's just get rid of the use of effect and we'll say we want tracking to run once and so let's just say is passing as a problem we pass in this tracking function and we only wanted to run initially once but you'll see it has a missing dependency tracking you might think this is the function it's never gonna change so but so you be fine you know putting the tracking in here so this would only run once however if your tracking function change maybe there's some other toggle feature that changes the kind of tracking it does this wouldn't run again so you might he might run into a problem there again you probably never only want to run something once you always want to run it whenever somebody's changing however if you truly truly believe that this should only run once what you can do is you can create you can set its initial state whenever it has fire so we'll say Kaunas tracking has fires and I'll say set tracking has fire okay you stay false and now whenever the tracking fires we want to set tracking a fires through and then we only want to fire this if tracking has fired who's boss now we're gonna get the dependency exhausted dependency warning saying that we're missing some tracking has fired so whenever tracking is fired this will run again but now this will truly only ever run once because once you set it it's never you know that the state is only against at once because it's inside of this component so you can truly believe that tracking will only ever get fired once so that's how you set things only once you do have to wrap it in a conditional make sure you set the state so that it doesn't happen again all right so that's kind of it for exhausting dependencies always follow the rules you're never disable that even though it might seem annoying my co-workers sometimes call it exhausting dependencies instead of exhaustive dependencies because it can be exhausting to work around this but just know it is for your own benefit for your code bases benefit for your co-workers you don't know gonna be working in this you don't know what features are gonna be important in the future but if you follow this rule this will vastly help you reduce bugs in the future I've definitely run across multiple times where this has saved me one thing to note that while we're on the topic here of setting state within a user effect is that this can cause infinite loops very easily so for example we did not have this logic here and we just you know for something but it's kind of a bad example for this but if we were just to say the opposite of tracking I've fired we're gonna run into an infinite loop and I don't want to do that because this code sandbox this kind of read try to run that as soon as I type it but if I were to finish typing tracking house fire the opposite of it this is gonna be constantly setting the state because the effect is gonna fire it's gonna change the state one of the state changes I'll use effects fire so I'm just going to see that it it's just going to set it again and it's going to be an infinitely be very careful especially if you're on like code sandbox or something because your browser will crash and it's really hard to get it restarted so be very careful infinite loops by calling state into use effect let's see next I want to go over the cleanup function so let's go ahead and go to the index and we're going to load open this load up this cleanup file so this cleanup function what this does is it runs another function whenever this is about to be removed from the Dom or unmount so initially we are adding an event listener called click that alerts whatever you click anywhere and then we want to clean this up because if this component we're unmounted if the page were to go somewhere else we don't want this to still be here so in order to do a cleanup function you just return within your use effect the function you want to run when this component gets in the mouth in this case we want to remove the event listener click OK so lastly we want to talk about using multiple different effects for your component because there are times when you want multiple different effects to happen but so traditionally like for example viewer to use the component did mount you would have to have like 50 different you could potentially have 50 different things in component did now because that's the only place you can put code that fires initially with use of fact you can create as many use effects as you want with different dependencies that fire at different times so let's take a look into the multiple I already have it running here so in this multiple example we have basically the combined components of initial of the basic and the cleanup so we have this use effect that is not updating the drive API you see the practice still counting every single time take component updates and we still have the event listener in here okay I say you're gonna see we're using multiple different back so it's very important to break up your effects based on what dependencies you walk if you want everything to run whatever the account puts updated make sure you put the count and the dependency of this one but this use of fact isn't going to get fired well that's this is actually going to get fired every single time the component update so you might want to put a tenancy array of an empty array that way this will only fire on the initial load since there are no external dependencies in this effect it's perfectly fine to do an empty array we're only using the document api's and these aren't stable enough that they will never change and so but this effect will only fire once the count updates that way these are firing independently of each other and we can still optimize everything so I hope this video wasn't too confusing I hope it helps I hope this helps you use the use effect hooks efficiently remember always put your dependencies in your effect and always follow the EU slant exhaustive dependency who those are the main things believe in it trust in it that is going to make your code future proof if you like this video make sure that like but if you disliked it don't dislike the video just put a comment on how I can do better that would be super helpful and maybe I can make something that would actually help you and other people if you want more videos like this of course that that subscribe and click that bell to get a notification if you're into that kind of thing otherwise goodbye world
Info
Channel: Web Dev Profesh
Views: 488
Rating: undefined out of 5
Keywords: react, useEffect, hooks, react hooks, react useEffect, javascript, useState, react performance
Id: Th7cjFHn3aU
Channel Id: undefined
Length: 15min 33sec (933 seconds)
Published: Sun May 10 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.