Advanced React Hooks - React Mastery Learning Path Pro Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone welcome back to a brand new course in react in which i want you to understand exactly how react hooks work internally and how you can become a great react developer by making the best use of them this course will be followed by a advanced react pattern course which you can again find on codedam.com learning paths go down to react mastery and here you are as a lead member if you are a member from code damn you're going to have access to this and any other course you see in the react mastery learning path so you're going to get access to basically everything you see here from the link in the description if you're a code dam member so that's all for the introduction part let's get started with the material from the next one hey everyone welcome back and let me just go ahead and quickly show you how you can practice the course along with me using the code damn playground so if you go to your dashboard right here you're going to be seeing a link which says playgrounds and once you open that you could see that there's a react 16.13 playground which you can open opening this playground will give you access to this particular interface where you can just play around with stuff you know if you have a thought if you want to create something you can do that extremely quickly from this particular place so we're going to be using this particular interface to you know just explore react even more and how it works and you're recommended to do so as well if you want to set up a local react setup that is also completely fine you can make use of create react app or you know snowpack or anything you want basically but get started with it so yeah once we have the environment set up let's just go ahead and get into hooks hey everyone welcome back and in this video let's just understand why hooks were needed in the first place well you see in react there are mainly two ways to create components the first one is class based components and the second one is functional components for a very long time since react was launched the statefulness that is your component could hold internal state only with class based components and the way you create a class-based component is you say class button you know extends react.component and then you do all that stuff with render you return something and that will be your class based component right you can also add state in here inside your constructor function and do all sorts of stuff however this was never possible with functional components before hooks so hooks enable in very simple way hooks enable you to have stateful components inside stateful paths inside your functional components how we're going to be seeing that with variety of hooks you state use effect use layout effect all that stuff but the main hooks the major two hooks you have to understand very deeply and you know something which you would be using all the time i'd use state and use effect and we're going to be starting off with both of them starting off firstly with you state from the next video onwards so that is all for this one i'm gonna see you in the next video very soon hey everyone welcome back and in this video let's just go ahead and take a look at you state hook so first things first i'm just gonna go ahead and switch this to browser so that we have more space for the browser and next i'm going to show you how you can create a eu state hook so what you want to do is first of all you can just go ahead as an exercise we can just go ahead and say console.log ustate and let's say hundred as the value and what you have to do first is bring in this u state from the react live dd so you can do that simply using this and once you do that you're going to see that if i open this in a new window if i inspect this inside console we're going to be seeing that well we have a console we have a couple of consoles actually and this says 0 as the 100 value and 1 as the function so what does that mean that means that this returns an array number one that is our observation and the second observation is that this array right here if i try to do console log array you're gonna see that this array right here would consist of the first value as the value which is passed here already and the second value is a function so now you can go ahead and destructure it into something like gone state is equal to array 0 and const set state is equal to array one right and just to keep syntax smaller and much cleaner the convention is to just destruct it right here so you can do that because of the es6 syntax so this just means that you state returns an array with two values that is the first one is state which is exactly what you passed here there are uh you know this is not entirely true so we're gonna understand that later on but the state is exactly what you passed here you can assume that for now and the second value is a function which can help you update the state value now one thing very important to you can see here is that i declared the statement as const that means both the state and set state values are going to be constants that means you cannot assign them a value by equal to sign what do i mean by that if i go ahead first of all let me just go ahead and give it an h1 of state like this so now if i do that refresh this right here we will be able to see that we have hundred on the screen what i cannot do is do if i want to change this for example if i do on click something like this i cannot say state is equal to 200 right why well i could say that but if i go to like refresh this and if i click on this in console you're gonna see we get an assignment to constant variable error right now you might argue that this is obviously because i'm using const so even if you use let here just to you know allow this to happen still if i click on this you're gonna see that although the value has been assigned you can just do console.log state here value has been assigned what you're going to see is that this value is not updated on the screen why because react does not know that you have changed the state variable this is a regular variable react is not monitoring this variable or anything right so when you update it react does not know that hey you have changed the value the way you inform react about that update is that you call this set state function right now this could have been like one way that you update the state and then you call it but what react does instead is that it asks you to pass this value this updated value the value which you want to set inside the set state function call right so just like inside you state you pass in a default value you can pass in a default value similarly when you set a state you have to pass a value which should be a new state right so in this case if i pass 200 and let me just go ahead and remove this for now we're going to be coming to that later on so if i pass this as 200 you're going to see if i go ahead and refresh this if i click on this now it changes to 200 on the screen as well right now the reason i removed this console.log statement is because i will be discussing um the exact workflow of how uh the state updates and everything later down the video but for now that's all you can remember that if you want to update the state you're going to make use of the set state function so yeah that's pretty much it for this video this small introduction video i'm going to see you in the next one we're going to be moving more into use state hook and different ways to initialize variables hey everyone welcome back and in this video let's just go ahead and understand a very important concept and that is lazily initializing state in react now what you can see i told you that you can go ahead and pass a default value inside this but there's a catch the catch is that this value can be anything or a function so i have decided divided this value which we pass into two things anything else and something which is a function right so if you pass in a function here for example function like this or if you want an arrow function lambda function like this or maybe this could be a separate function all along you know const lazy value something like this this is also fine and you can pass in lazy value like this so whenever you pass in a function what react will do that will check that hey if this is a function i'm going to call this and the value it returns i'm going to set that value as the initial value of stuff right so if i go ahead and return this 100 right here refresh the terminal you're going to see that we get a state of 100 well on clicking it becomes 200 if i return let's say hello right here refresh you're gonna see that we get a state of hello now why would you do something like this and not directly hello like this well it would work obviously it will work just fine like this as well and this is absolutely fine you do this if you have a singular expression which is let's say computationally expensive for example you do a json.stringify of not really stringy5 but maybe like bars of something like this now this is also completely fine i mean there's nothing wrong with this as such but the only problem with this is that every time the state changes this function gets executed why because this is inside running code it has to evaluate it anyway because when this u-state function was written it might be written in a in a something in a this way that you state the act.u state is something like this initial value right so the authors might have written this in something like if type of initial value is equal to a function then call it right and do something with do something with it and if it is not then maybe just do something with initial value in either case if you do a json.parse of something like this so when the type of this is being evaluated the function call has already been made that means this would be made over and over and over and over again because if this is a function and first time you know this this is an important part that if this is a function and if this is first time then we evaluate it otherwise we ignore it or maybe like you know if this is not the first time we would ignore the value but if you have a constant expression which is actually a call to a function in itself then it is a problem let's take a look at a very simple example to understand that i'm going to go ahead and do a console log of hello world here right and that's it and right here inside set state let's just set the state to math.random so that we get a trigger a re-render on every click let's go ahead and refresh this tab which is again pretty much the same thing which has already been opened and you see that we already get two hello worlds here right we already get two hello worlds if i start clicking on this you're gonna see that we get more and more hello worlds although this value ideally should be the initial value of the usted hook still we get all these hello worlds because react would anyway call this function again and again whenever the render happens we're going to be coming to that in a moment in some other video but what you have to understand is that whenever you call a set state function or set something function which is a you state second argument you trigger a re-render of state a re-render of the function given that the state is different right because if i set this to 200 for example and if i go back refresh this if i click on this we get a trigger first time and then when i keep clicking on this nothing happens right so that is why i needed math.random here so that i can trigger multiple updates and then we will get multiple console logs in this case we do not get any more console logs because well the state is not updating so react does not read into the function what you have to realize here is that if i try and put this console log in a lazy initializer then if i refresh this you're gonna see that this happens only for the first two times and now if i click on this this never happens again and this happens for two times because well it renders it re-renders again because of the react strict mode because in strict mode react tries to render your component again just to see if there are any side effects so that it can inform you we'll discuss this more in the advanced react patterns course but for now if you remove strict mode out of it refresh it you're gonna see your component is rendered only once which is helpful because we don't really want to bother working with twice the amount of logs so anyway now you could see that if i click on this well if i change this to math.random and if i go ahead refresh and click on this nothing really happens right we don't really get any more console logs and the reason for that is that your state is lazily initialized because now it just sees the next time when the component renders re-renders it sees that well this is a function which is passed therefore i don't need to re-render or maybe like i don't need to call this function at all because i already have the stored value from the function itself so that is why it will not call the function again but this means that inside you state you cannot really store a function right because well if you store a function it will execute it if you try to store a function to execute it and then you'll lose the results right so there are ways to store this and that is you can have a function which returns a function so what react will do is that it will call this function and when you call a function which returns a function you get a function now this might seem a little weird but if you do hit this enter you can see you get the inner function because you called the other function and that is exactly what react will do and then it will store this value which happens to be a function inside your u state hook so that is all for how you're going to initialize the use state lazily and in the next videos we're going to be learning more about you state how they exactly work and how to work with other hooks in react hey everyone welcome back and in this video let's just go ahead and take a look at how you can update your state variable so let's say we start this as a counter application why not so we have a counter set counter very simple stuff and inside h1 whenever i click counter is let's say this is a counter so whenever i click i want to update this counter right so one way i could do is that just like we saw that set state accepts um you know anything you want and that will be the new state right or set counter in this case so once we do that once i refresh this you're going to see whenever i click on this this counter works absolutely fine right and obviously you would expect it to work as well however what else you can do with the setcounter function is that you can specify the argument instead of a value as a function right so what is going to happen is that now if i have let's say um you know instead of creating a function out of the thing we can also pass it a function like this so now if i return it a value that is let's say 50. react just like it does with the lazy initialization function it will also do the same thing with the set counter function or maybe like set state function whatever you want to call it so if it sees a function is passed inside the setter it will execute this function it will get the value which is returned and then it will set this now you might ask me that what is the use case of this so first of all let's just click it and verify that yes in fact this is 50 now and it is not changing whenever i'm clicking on that the use case of this is that this function right here the first argument is going to be the value which the react internally knows is the value of this uh it's the counterpart of this setup function that means the first value if i go ahead and put value here and if i put value plus 1 this value right here is the value of the counter itself and let me just go ahead and refresh and tell you why that is the reason so now if i click on this you could pretty much see that this works similar to how count plus one worked right now you might ask me that hey or like not really count but counter plus one you might ask me that hey why do we need that anyway right because you already have access to counter you already have access to the updated state so why would you need that well the reason for this and there's a very good reason for this first of all this will help you very much with the use effect hook which we'll cover um very soon in the next few videos and second of all at the moment i would request you to just keep this thing as a thought in mind that whenever your state your next date that is the updated state depends on previous state that means you need your previous state to calculate the next date whenever that is the case use the functional method right return count plus one now you can have this as value doesn't really matter because this function right here would be called by react internally right so internally internally what react would do is say set counter and if it sees a function like this is this might be the definition of the react set counter function it will see that hey this is if value if type of value is a function it will say then go ahead and execute value with the newest state value right and then you know return value as a new state value and then we'll just set that as the new value but what i'm saying is that you know in this case you can see that well because we are creating a counter which increments it depends on the next state right so you need 14 uh you need 13 to create 14 you need 14 to create 15 because that is the next value right so in this case you need it therefore make use of the functional notation if you don't need it if if the previous state does not depend on the next state then you can just go ahead and directly set it so for example if i refresh this now you know this would work just fine because well the next state is completely random and it does not depend on previous state if you want to do something like this that is also completely fine but this is not required right and i'm gonna show you an example maybe in the next video why this is a good approach if your uh next state depends on the previous state so this is like one way of updating values in react and you should understand that when you should use it you should use it whenever your previous state depends whenever your next state depends on your previous state that is the ground rule so yeah that's pretty much it for this video in the next one i'm gonna show you an example of when this will be helpful and when this will fail hey everyone welcome back and in this video let's just go ahead and take a look at when exactly the set counter will not work and when will you need uh you know this approach now almost always if you do not know what you're trying to do just like i said in the last video the rule of thumb is that if your next state depends on your previous state you almost always want to do this approach right let's see why first example is i'm going to create a set timeout here right just to introduce some delay so i'm gonna say after one second whenever i click on this then do a set counter of counter plus one right so now if i go ahead and click on this you're gonna see that after one second it updates the value right let's just go ahead and copy this out and paste it right here so now when you think about this what do you see well you see that first of all let's go ahead and update the counter so in your case if i refresh this the counter will go from 0 to one and here you might think that hey i want to increment the counter again so it should go from one to two right wrong let's just go ahead and click on this so it goes to one but it never goes to two why is that and as a matter of fact if you do a let's say 500 here then also you would expect this would go to zero to one then this will go to one to two and then this will make it go to two to three right wrong let's refresh this again click on this and you're gonna see the counter always stays on one now to understand this you have to understand how react functional components work well in react just like i told you in the first few videos i'm not going to give you an in-depth look of how the function re-renders that is going to happen in advance react pattern course so wait for that but in this video i'm just gonna give you a brief overview of how this happens so what react sees is that whenever you call set counter as a function it sees that hey there is a state update it will internally compare if there's any change in the state and if there is or if it feels like re-entering it'll re-render the component right however what do you mean by re-entering the component re-rendering the component means calling this function right so what's happening really is that your ui your ui is calculated every time for example the app component has changed so we're going to call this app component react is going to do that internally and your ui is created and you can think of you know react saves to browser browser go paint this ui right this your ui thing so react does this particular stuff now when you do something like this what is happening is that inside a particular function call when this function was called for the first time this function had the counter value as 0 right because that was the initial state then when somebody clicked on this you read this counter which is still zero and you set this to two or you know zero plus one that is one however after 500 milliseconds you are still reading the same counter right so you know you are still doing zero plus one you are not doing one plus one even though you might think that counter is a state variable and i have already said counted one this one right here becomes counter only when react calls your app function again remember that your ui is calculated only when react calls your app function right so when you call set counter it updates it to one this this value is not counter of the current function this is super duper important thing to understand deeply how the usted effect used hook works why this one is not a value well for starters you can think of because you cannot really assign counter as one because it's const that is why i prefer to keep hook values as const because they convey the meaning that this is immutable that is neither react nor u would change this value right so once you understand that once you realize that that this set timeout runs with the same counter variable you get that right because you know you know that this variable this value is not changed this is still zero so you have effectively you have zero plus one zero plus 1 0 plus 1 all the way here right now let's come to functional uh sort of update inside the set counter variables or the set count of functions so instead of this let's just go ahead and do a counter plus one right and see that i'm still using the local variable so obviously you should now by the time you should now have realized that this is no different than the previous code snippet which we had right well i clicked on that twice that's why it happens so let's just go ahead and click on it only once right so you can see nothing really happens and the reason nothing really happens is because you're still using that old stale value which has now been flushed out so how do you fix that well you supply or maybe like just like i said use the updated value right here now whenever react is calling this function for you whenever react calls this function on your behalf you know we have seen that react will see that if this is a function it will call it with the newest state value because react internally knows what is the latest state value right so react knows that well whenever whenever you know it has to call this to update the new value update the new state react will automatically specify the latest value of state so if i go ahead and refresh this now and if i click it on it once you can see that it changes to three and the reason for that just like i said the first time it changes to zero to one the second time it changes to one to two and the third time it changes from two to three right so you can see right here is the transition and the reason this works completely fine is because every time this function right here you know you can extract this function and say this update value like this and you can go ahead and you know probably give it something like this this is also fine the reason this would work just like i said is because react knows what to put in here react knows that hey the latest value will go automatically inside that particular argument so yeah that's as simple as that i hope you understood how the um functional update in a use state hook works super important stuff and the only thing you can take away from this one is that whenever your previous state depends on your next state i always speak that in a wrong direction whenever your next state depends on your previous state you should use this particular approach right because this will help you not to get that those troubles of um you know using a stale value of state if you have timers or you know if you're somehow jumping out of the reactive way of doing things so yeah that's pretty much it for this one and i'm gonna see you in the next video hey everyone welcome back and in this video let's just go ahead and take a look at how we can recreate that this dot set state from class based components so let me just go ahead and clean this up real quick and what i'm gonna do is i'm gonna tell you a little bit about what this dot set state was right so if you had a class based component like button extends react dot component so if you had something like this what you could do is if you have let's say div id counter something like this or maybe like not counter but this dot state dot counter and inside constructor if you have this dot state as counter as 0 and then what you could do is on click you only had to specify the variables you want to update right so you're going to say this dot set state is counter is this touch state dot counter plus 1 right so that's it that means that if you had a counter 2 right here and if you had at this dot state dot counter 2 this will not affect the state call the state update will not affect the counter 2. so let's just go ahead and see if i just go ahead and embed this button right here which already brings in its state so if i go ahead and do that you're gonna see that well we are lacking a super call here so once we do that you can see now we have two numbers and we could change this to h1 for a little bit more readability so now we have two numbers so when i click on this you know the second counter works just fine right so if i have even i have counter as 10 this would work just fine so if i have the first counter would work absolutely fine but if i try to recreate the same example in functional components what we're going to have is state set state and i'm going to have you know counter 0 counter 2 10 right similar stuff this state is you state here then what i want to do is i want to have the same thing so i'm going to go ahead and commend this basically the whole thing and i'm going to have a return of this thing right here and instead of sets this dot set state i'm just going to say set state and i'm just going to say state dot counter plus 1 and this will also become state.counter and state.counter2 right so now you can see so far it looks fine because you know you just have a single thing and a 0 and a 10 just like we had in class based components but the moment you click on this you can see that the 10 vanished and the reason the 10 vanished is because it's the set state call right here it overwrote this counter to property why because you know that whenever whatever you supply inside set state would automatically be set as the new state so on the first window the first render of this app function your state is counter 0 counter 2 10 right so this is your first render state your second render state the second render when it when once the button is clicked the second window looks something like this the counter 2 has been removed from this so how do you reconstruct this behavior where you can just simply go ahead and supply something like this well you can do that but you have to be a little bit more clever for that so instead of having set state directly out of this what you can do is you can create a function which is you know just an internal use function and then you can have a function set state which would say receive new state right here and what this will do is that this will set state it will call the internal set state old state and you can return a new object which is the combination of old state and new state right here so let's take a moment to see what's happening here so what we are doing is that we are specifying set state which is this function which we are now calling as another function all together this is not your second argument which comes with you state right this is another function so this function right here accepts a new state which is object in our case and it calls the internal set state function however it takes in the uh you know the previous sort of state which is the newest state and it returns a new object and the reason we did this and not just something like state and new state is i hope you remember from the last video when i said you that whenever you want the next date whenever the next state depends on the previous state you should probably it's a good idea to use the functional notation of updating stuff so we do that and we destruct the old state we destruct the new state we destruct the new state after the old state so that the properties are overwritten which are which whatever properties are changed right and yep that's pretty much it so now once you have done that you can go ahead and refresh click on this and you're going to see that 10 basically stays just like it will stay in a class based component so yeah that's pretty much it and how you're going to recreate this dot state and set state you could pretty much now go ahead and you know basically throw anything in the state variable and you can just call set state with a limited number of things which you want to update and it will work just fine but of course i would not really recommend going down this way unless you know what you're doing because just like i said you can have multiple use date in a single function right this is probably a better idea if these are not like a lot of things to have a separate u state right so you can have set counter as you state zero and then you can have counter two set counter two as you state one or like you know whatever you want and then you can just maybe just update a single hook if you want but again it also has its use case the other thing the other syntax also has its use case so it really depends on what you want to do but this is like one way one analogy if you're somebody who has done a lot of stuff in class-based components so yeah that's pretty much it for this video i hope you understood something new something good and that is all for this one i'm gonna see you in the next video really soon hey everyone welcome back and in this video let's just go ahead and move on to use effect now userfix is one of the two most important hooks um i would say in react and those are like you state and use effect right so use effect allows you allows your component to be aware about changes so what do i mean by that whenever you update the state for example let's go ahead and remove this all along and create a counter set counter again so we can have something like return h1 counter right so this should also be inside the app class so that we just have some css with us so once you do this what you have to realize is that whenever the counter updates for example if i on click and set this set counter counted as counter plus one so whenever you do something like this what you have to realize is that your component gets updated right but how do you know the component is updated or maybe like if you want to do something whenever the component updates how do you inject into that life cycle you do that with the help of use effect hook now this hook right here consists of two parts the first part is a function right and the second part is a dependency array which is optional so i'm going to remove the dependency array at the moment and we're gonna just focus on this function now what i'm gonna do is i'm gonna go ahead and console.log console.log something changed right and that's it that's all i'm gonna say if i go ahead and open this in a new tab now go to the console you're gonna see we get something changed even though nothing really changed so if i click on this if i start clicking on this you can see that i get something change exactly one time uh more than our counter because that counter starts at zero and we already had something change already available so if i click on this you can see that we have something changed on every single state update so i can go ahead and say counter 1 as this and i can go ahead and say counter to for example if i want to create another counter as this and i can have let's say counter two set counter two and this could be just counter two or maybe like you know set counter 2 only because we are not using we are using the functional notation so that's convenient so now if i go ahead and refresh this if i start clicking on this one you're gonna see that we still get something changed console logged and if i click on this we still get something changed console log so this means that if you do not provide a dependency array that is the second argument this will always run whenever your component updates and when exactly does it run we're gonna see that in the life cycle sort of video which will happen very soon but what you have to realize is that whenever you use use effect without a dependency array it will always always run whenever this function re-renders this is something which you almost never really want because you want an effect to run against a particular value which is changed right you don't really want to monitor like you know unless you're trying to debug something or you know you're doing something or checking how many times the component re-renders you just want to focus on a single or maybe like multiple values not really like every single update so we're going to be taking a look at how do you restrict it using dependency array what exactly that is and how this works how that works in the next video but in this video i just want you to realize that the use effect is a function which runs by react which is you know react calls this use effect function every time the function is re-rendered or updated or you know react calls this function again so yeah that's pretty much it for this video i'm gonna see you in the next one really soon hey everyone welcome back and in this video let's just go ahead and take a look at the dependency array in the use effect hook now what do i mean by that that means that you can specify an array as the second value now it has to be an array or it has to be undefined nothing else but if you specify an array that means that you say react that hey look i don't really want to render i don't really want to call this function on every single render what you can do is go ahead and look inside this array and check the values which i have specified if those values have changed then and only then run this function so you see what you're trying to do here is that you are binding this particular effect to a set of values so you are just monitoring these bunch of values whatever you specify in here and yup that's it if those values change you read in the function you you call this function again if they do not you don't call them let's see so if i go ahead and specify counter here and if i say something change or maybe like just say counter one changed let's do that and go to this new tab refresh right here and see that the first update which you get is counter one changed even though that has not changed so with use effect what you have to remember the first time your component is mounted successfully a use effect call is run right it doesn't matter what you specify inside the dependency array the first use effect call will always run whenever your component is mounted right now once that is mounted now you can go ahead and change counter 1 by clicking on it and you can see every time you do that the counter is in fact updating right however here's the cool stuff if i update counter 2 you can see that this counter 1 changed does not appear right and the reason for that is that well you know whenever you click on this sure the counter 2 updates and the whole component is re-rendered however your use effect is not configured to run the function on counter 2 changes because you do not have counter 2 inside dependency array now if you go ahead and add counter two here now you can say counter one or two changed like that and now if you refresh you're gonna see that you get counter one or two change console log on this one add counter one or two change console log on this one as well so you can see it happens for both the counters similarly if you get rid of this at all you have to change this to something right and the reason for that is because not only it will re-render or and run this particular thing on count of one and counter two but also if say you receive new props from the parent or the parent re-renders right so in that case also this will render so it'll say something change something change so it'll work just fine again just like you can have multiple use states in a component you can have multiple use effects so you can have like counter one changed and you know you can have kind of two changed like this right so maybe you can do some logic here for counter two only you can do some logic here for counter one only right whatever you want to do it so once you do that hit refresh you can go ahead and see now right now you just get counter one change now you just get counter two changed and so on and so forth right there's one little thing you should remember here is that if you try to update your state inside use effect you might run into troubles right because you see if i go ahead and do set counter of counter counter plus one you see what's happening here is that you have created an infinite condition right so you see it keeps on updated updating and updating and updating all the way till you know whatever it can support and uh yeah it is not exactly you know it's not exactly rushing to infinity or anything because it has to do a lot of stuff but you start seeing um these sort of error messages that oh boy slow down slow down you know stuff like that so you don't almost always don't really want to get into a condition like this so don't really try to update i mean again if you know what you're doing doing it's completely fine but as a general rule of thumb if you see yourself updating the value of the state variable without any if else checks um you might want to revisit your logic right so yeah that's one thing about the dependency array the another thing which is important about dependency arrays is that these values right here are compared using triple equal to sign right inside the react library this is super important because now you cannot really use objects right here so for example let's say you have an object which is hello one right you see you're not changing this object nothing is happening and you just have a single let's say counter and an object dependency and you say console.log counter one updated right which makes sense because you know you could see that counter is um you know a state variable which you're monitoring an object is a simple object which just has hello one property however if i go ahead and open this in a new tab if i inspect this go to console if i click on this we get counter what are updated which is completely fine but if you click on counter 2 you will see that you get counter 2 updated as you know counter 1 updated as well at the same time you can observe that counter 1 was never updated then why it is happening why is it happening well you see that in the last video we discussed briefly on how react really works with functional component that is it calls your function component again and renders the stuff with the updated state values but here when it calls your function again you're gonna see that objects in javascript are never the same that means even if they have similar values you're going to see they returned you false this is false because this object right here if you have x as the variable this object right here in the memory represents is represented somewhere else right and y is represented somewhere else as well so if you think about it x might be you know something at zero x a b c d e f right and y might be at zero x one two three four five six whenever you use x equal to y or x equal to y in objects in js with objects in js javascript internally always compare the memory address locations right so if even if x and y have same properties same values everything same they are still not equal because they are memories memory addresses do not match so x equal to y will always be false y equal to y will be true because they obviously they refer to the same memory in the space similarly for x equal to x now whenever the function re-renders this object is created again for that particular function right so once the component mounts react says that hey this object is not the same as the last object therefore i need to re-render this you're going to see that if you move this outside this problem gets fixed because well you know every time now you have the same object to refer to if you click on this you can see this problem is not there because you're not recreating this object but if you move it right here then because you also have this as a dependency array value this will trigger your counter one update changes so you have to be very very careful interestingly this will change if you have this as a state variables so if you have obj set obj like this if you throw this inside a u state what is going to happen is the very first time on the very first render react is going to uh you know store this value inside this variable and from that point onwards it is not going to refresh the value that means it's going to reuse the same object so if you refresh now if you click on this counter 1 gets updated but if you click on this counter 1 stays the same right so that means you could technically technically you could have a behavior where um let's say if you want to preserve the memory location of an object you can throw that inside a u-state variable right and then this object always refers to the same object unless you modify it so yeah that's a little bit of information you might want this representation and actually just extracting out object out of this and mutating object refers uh very closely is similar to another hook which react provides that is use ref we're going to be understanding use ref later on but for now this is how you can preserve the memory location sort of of an object inside the functional component itself while maintaining it inside your dependency array as well so yeah that's pretty much it for this video i'm gonna see you in the next one hey everyone welcome back and in this video let's just go ahead and take a look at the final piece of the puzzle inside use effect hook and that is the cleanup function now what we have seen so far is that let's see we have let's say the app one is the let's say this app first render is something like this then a state change happens then what happens is that you get a second render of this app function again right so the use effect use effect is called after mount and again in the same in the same re-render if the use effect includes a dependency which has been changed the use effect is called after the render right however what happens is that when this transition has is happening from one to two you might want to do some cleanup for this particular function right for example let's say you have established some listeners or you know some event listeners or something you which you might want to clean up right so react gives you the opportunity to run that particular cleanup code just before the transition happens so what do you mean by that that means that you can return a function right here you can name this function if you want and this function right here says cleaning up effect of counter one right so what do we mean by that well let's just hop back to the demo and now if i see we have a counter one updated but we do not see cleaning up effect that is because the cleanup runs only when a function is about to tear down the ui of a function is about to tear down and another one is going to take its place so if i click on this you can see i see a cleaning up effect of counter one and then count one updated again so what you could see is that this runs the first time this runs the second time and this runs the second time as well right so the very first time only this runs once i click on the counter this runs and this runs the reason this run is because the first instance the first ui of the app is going to be teared down and the tier down was because of the variable which was about to change if i go ahead and do the same thing with counter 2 you're going to see nothing really happens because this effect does not care about counter 2 at all however if i click on this again you're going to see we get a clean up effect of counter 1 and counter 1 updated again right if i click on this clean up effect again and count to one updated if i click on this clean up again count one updated this is super useful in in the sense that for example when we'll be seeing about creating custom hooks we're going to be seeing how you can use a callback or a clean up function like this so yeah that's pretty much it for this video in the next one we're going to be taking a look at maybe how you can get started with custom hooks and we can do a lot of good stuff a lot of damage with just these two hooks alone so yeah that's pretty much it for this video i'm gonna see you in the next one hey everyone welcome back and in this video let's just go ahead and take a look at the life cycle of hooks and how they are called especially the you stay and use effect hooks so you can see that i have console log spread all over the place but just to walk you through real quick we have a child component right here which has console log inside the use effect and the cleanup function right we have console logs inside app all the way we can actually have console logs here too why not we can say child rendered right we can right here say child rendering complete and we can say this is child component and return oops not return but cons child component is this h1 dag right as simple as that so now this is completely analogous to its parent component so you can see in the app component the first line we have is console then inside use state i'm using lazy initialization just to see when these console logs will appear similarly inside use effect we have a console log in the cleanup function we have a console log and before we return the component we have a console log so now let's just go ahead and refresh this and we're going to see some interesting result first things first i am a child is visible right now the reason this is visible is because show right here becomes true on the first use effect call right so let's let's just do one thing what we're going to do is i'm going to say if counter is equal to 5 let's say i want to set set show as true right so now if i go ahead and refresh this we're going to have a little a smaller render console logs so the first console log which we get is app render started which is obviously what we'll expect once the function is called the next one you can see is lazy in it one called now this well technically speaking this is lazy in it lazy function inside you state however this is called immediately and the return value is set as the initial value the sort of the reason this is lazy is because this will this function will not be called again at all right as long as this component is mounted the ustate functions will not be called again why because they have served their purpose and we have extracted out a default value from them so this is the reason these functions won't be called again but they are called the very first time so once these are called you're going to see lazy unit 2 as the second value so that's fine then finally you can see that app render ended is called so you can see right here we just called we could just call app render ended casually and you would expect that to happen as well because there's no such console log going on inside this app component because show is also false so the child is not rendered therefore we do not get these particular statements right here now once the app render is done you're gonna see we get a statement called counter updated and the reason for this is that you can see the use effect right here which includes the statement called counter updated so what you could see from this thing is that use effect well technically this is not um you know you won't be able to see it exactly but you can have my word on this that use effect would run when your component is mounted on the screen and your component is available to the user that is the pixels are displayed on the screen how we can verify this is i can go ahead and put a debugger statement right here go to console refresh right here and wait for it to pause and you can see when it's paused on debugger inside the console you still have the four statements render lazy unit 1 2 another app render ended however you can see that on the screen you do have the contents pasted right you do paint it not really paste it so the browser has already painted the contents for you now whenever you click on this plus you can see that the counter updated is called because the debugger um is is there right now once that is done let me just go in and remove this real quick because we don't really want to have debuggers all along so once that is done let's just go ahead and click on the counter so just to add a gap here i'm going to click on this and you can see that we get two things app and under started app render ended cleaning up effect of counter and counter updated now why is that because when you click on this you set the counter to the next value because counter is a state variable you can see that react would internally call this function that is to extract the ui the updated ui again so react will call this function again which will run app render started right this time you see that we do not get lazy init call because react knows that hey i already have the value for the state variable uh from the first one from the earlier run so i'm just gonna restore that if if this value is not changed if this is changed i'm gonna you know just return the latest value in this case so you can say that in this one in the second case your counter is one that is the reason it is just playing one right right here right because the value in fact is one then app render ended basically just means you do not hit any of the lazy in it and once the app is rendered on the page this use effect cleanup runs right so this is important right here in the terms that once your component is rendered again the cleanup from the last component happens what does this mean this means that i can have a debug of like value right here for example so i can say value right here right so now this will make things a little bit more interesting so now if i click on this you can see that the cleanup which has happened is of value zero not one obviously right and the counter updated which happens is of value one so if i have value equal to counter you're gonna see that now if i go ahead and refresh and if i click on this you can see the counter updated right here happens for value one but the cleanup has happened for value zero which makes sense because the function which was mounted earlier was for the value 0 1 right and the counter has been updated for value 1. so the use effect the latest effect includes the value of 1 but the cleanup which happened was of value zero so once that is done that is all fine now i can have something like this again so if i click on this again you're gonna see you get a similar thing again again but something interesting is going to happen on count of five right because we're gonna be setting the child to true that means this component will become available so let's just go ahead and click on this now you can see the following things happening apparently started apparently ended cleaning up effect of 4 setting the counter to 5 which is again absolutely fine apprentice started apprentice ended child child child so what's happening here well you see that what we did right here is that first things first you set the counter which resulted in a re-render then once the counter was updated you re-rendered the application again in this block right so you set something in this block because of this thing the app component re-rendered again so you see this this thing right here this thing happened because you set you called the set show and set it to true so the moment you did that app render started again right which is completely fine then you know we skipped the lazy unit calls obviously just like we discussed before app render ended however you see that the child rendering begins after we get this app render ended console log now this might confuse you a little if you are thinking that hey how can app render end before the child logs are available right so according to you you might think that you should have apprentice started then these three statements and then app render ended right but what you have to remember is that when something like this happens this is transformed internally into um you know something like react.create element and then uh not really jsx but something like this right so this is what is happening internally so what react is doing is react.createelementdiv with class name this these are the children and then this is something react is doing right so this app component is pretty much like a react dot create element app and then props and so on and so forth but it is totally up to react to determine when it wants to actually called the child function right so react create element internally will somewhere down the line call this child function somewhere down the line we'll call this child function with appropriate props and values and all that stuff but before it calls that it just has that you know sort of markup and react will call it once you return it from the component right so this means that if you are doing even if you are doing something like const child component as child like this and if you do something like this then also react is not going to mount or you know call this function or you know you're not going to see any sort of locks if this component is not really really displayed on the screen right so that means this sort of thing is actually free to do you do not hit any computational uh sort of uh you know bottleneck or anything of using components before you render them or maybe like displaying them like this before you name them because react never really calls this component unless this is not really rendered on the screen so this time it was in fact rendered on the screen so that is why oops it looks like we actually refresh this so now you can see that is why app render ended gets called first because well technically speaking the render has not really ended the render ends when you return the component and react renders and on the screen so once that console log is done then the child rendering starts and as usual you're gonna see child renders child rendering completes just like app happened and then once the component is mounted you see the child updated console log right and if i click on this again you're gonna see that um we get app render started again because of the counter app rendered ended again because of the counter and yeah actually this i am a child will remain visible because we do not set this to false so let's do a set show false something like this right refresh and now click click click click click and you're gonna see that we get the child console logs just like we would expect them and the next time you click on this you could see something interesting you can see that the app render starts app render ends child rendered why because child is also the part of the tree right so once this happens once this uh counter is updated the app re-renders the child component is also visible the show is not false right now right the show becomes false once the component is mounted and once this effect runs again then counter is not 5 anymore counter is six that means this runs and then again the car the component re-renders this thing runs and this counter becomes six this show becomes false this was six before as well right this becomes false and this is unmounted right so this is literally now not on the screen so when it was on the screen that is just after the counter has become six but the show variable has not become false you get child render child rendering complete child cleanup called why because well it is a use effect without any dependencies and child updated right so you can see right here that cleaning up effect of counter is called next where the counter updated value becomes 6 and the show variable is set to false now once the show variable is set to false you can see that app render started again apple under ended and the child cleanup is called only the child cleanup is called not the child updated and child rendered and all that stuff and that is the reason is because your component is unmounted just like on mounting the very first time the child updated appears similarly react will give you one last chance to do anything before the component is unmounted and this is the place where you'll get your one last chance that is the cleanup function of a use effect sort of hook right so this cleanup function will run irrespective of if you have any dependency array or not right so for example if you have a cleanup function in the counter one this cleanup function will also run before your app component is unmounted similarly for any other thing which you're doing in the nested child components as well so yeah that's pretty much it on how the whole life cycle works and looks like that's all for this video i'm gonna see you in the next one hey everyone welcome back and in this video let's just go ahead and take a look at how you can run asynchronous code inside a use effect and how you should do that if you want to do that we're going to be doing that with the help of making a fetch request now this is not a react pattern you should follow but this is just a demonstration of how it could be done you should probably take a look at the advanced react patterns course if you want to actually know how to make use of fetch request effectively and efficiently in a react component so you can find that course in the react mastery learning path but for now let's go ahead and stick to this so i'm going to be making making use of this use effect right here and if i have not told you before if you specify an empty dependency array you can pretty much just run this function right here on the very first time that's it on the very first time of the function when it is mounted right so yeah that's pretty much it this could be um you know you could argue that this and you state something like this this is equivalent funnily enough right so this is equivalent sort off to this one the only thing is that you would not get a callback or a cleanup equivalent in the use state sort of thing and plus this is a ugly hack to be honest you should always use use effect if you want to run it once if you don't want to run the some sort of code once the component just mounted and yeah so let's go ahead and really quickly inside our public folder i'm going to go ahead and create a data.json file and i'm gonna say this is just hello world that's it so not really anything interesting but now i can go ahead and take a look at data.json like this which is going to return me hello world this is of course will be different for you depending on how your playground looks like but anyway i'm just going to make use of fetch right here and i'm going to say then text is text.json and then we finally have the data which we want so one thing which you can see right away is that we would not want to do something like this right and i can just show you message message you state empty string and i can say message like this right so i can say set message data pretty much dot uh hello right because that is the property now you can see it technically works it technically works but you should not really follow this convention and bonus points if you can think why right because you can see we already have uh you know a warning already so it actually provides you an actual solution as well so i'm gonna tell you really quick why that is the reason you see when you make use of an async function what happens is that by default in javascript the moment you make a function async it automatically returns you a promise right so it returns your promise and remember what do you remember that what use effect function should return yup that's a cleanup function so instead of a cleanup function something which should be a function in the first place you are returning a promise value that is why you get a warning as well and you get a possible solution to fix that as well so we can follow a possible solution and that is async function fetch data for example have this as this and then just call it randomly you know not randomly just casually right here no need to return anything or any any sort of stuff because if you return it then it is a cleanup function which will be called later on right so now you can see it works perfectly fine and that is how you should exactly do so anyway i hope that clears up the question of fetching data asynchronously inside a use effect hook and i hope that helps that will be all for this video i'm gonna see you in the next one really soon hey everyone welcome back and in this video let's just go ahead and take a look at use ref hook in react now use ref hook is pretty awesome in the sense that you have access to an object to a property in an object which you can mutate now hear me out first things first let's just go ahead and import usref from the react framework and you can do it like this next is you go ahead and create let's say um i don't know obj is use ref and then write anything anything you want 100 or 123 or whatever right and yep that's pretty much it so let's just go ahead and throw this inside a use effect or maybe like not even in a use effect let's just go ahead and console.log the ref object right right here so now if you go ahead and refresh this right here you can see the ref object holds magically holds an object which has a current property and a value hundred right now what happens is that let's say if i have um you know i don't know something like use effect which runs whenever the obj changes right now we remember you remember that uh inside the dependency array of use effect it uses the triple equal to or double equal to whatever triple it uses triple equal to actually um to check for the dependency changes and because obj is an object with a current value of 100 we know that this effect would run if this object is being recreated right on on any state change or whatever so we can say effect ran something like this and let's say if i on click on this i just set counter to a value plus one right let's just quickly create a counter set counter why not that's like a standard state variable for us and i can say counter right here right so now if i go ahead and refresh this you can see use effect is not defined let's bring in use effect you can see that if i click on this we get the counter increase and we get an empty console lock for some reason because of this let's remove that refresh and now you can see that we do not see the effect run console log running that means on every single render every single new render which is happening this object is not changing this is important so what's important is that user f on every single render will always return you the same object so this means that you can store anything you want here you know any number any string anything you want here and on every single render you're gonna have the same object and the value can be accessed using the current property and not only just accessed but also modified right so so as to say for example let's say you want to have um whenever the counter changes for example use effect whenever the counter changes you want to say i want to multiply object dot current i want to multiply it by 5 right and let's say you have a value of 5 here so what's happening here is that you just multiply the object.currentvalue and yeah that's that's that's basically all you do and you can just say console.log new object ref is obj right here now if you go ahead and refresh this you're going to see that if i click on this we get the new object ref has current 125. if i click on this we get 625 that is 125 times 5 right if you click on this again you get 625 times 5 and so on and so forth so what's happening here is that you can see object dot current can be mutated but if you just you know if you just try to update the object dot current value it will not trigger a re-render so if i go ahead and comment this one out and just do something like this and say you know something like this two and one just to distinguish them refresh now if i click on this you can see that all we get is a newer if new object riff and that's pretty much it nothing else we see that there is no update no render running no effect run nothing is happening right you can also make it like this so that you detect every single re-render and even now even when you're detecting every single v-render you see no rearrangement is happening because when you mutate the current property inside a usref thing nothing really happens right because react does not inform you about changes of this current property so what's the use case of this well you can think of use ref and using this thing as sort of storing a mutable value inside your function um you know inside your function component function right and why would you want to do something like this instead of storing it in a global scope well you get free memory cleanup right right here for example let's say you are storing some uh heavy you know heavy json object maybe like this so your current value would consist of all that heavy json and then once your component is unmounted this memory would be freed right however if you have an object which is like this this memory will not be freed because it's in the global scope of at least this component file right not if in the whole scope but it is still in global scope so this is like one use another use is that you can actually attach the ref objects to the elements as well which is sort of another use case which we'll see in the next video but let's just keep this one to just the simple mutable application of the riff use riff hook so that is all for this one i'm gonna see you in the next video hey everyone welcome back and in this video i want to quickly show you a use case of use riff and that is to get access to dom elements directly now you know that in react the reactive way of doing things is to not really interact with dom directly that is not really use document.getelementbyid and you know query selector and stuff like that directly but sometimes there is no other way right you need to hook into your dom element so one of the ways you can do it and still keep it sort of reactive is to make use of a ref and that means that if you have let's say this other not really let's not keep it div but let's give it to f and if you go ahead and do a ref attribute like this if it's confusing you i can also say that this is element ref this does not really matter so once you do that and once the render completes what you can do is you can go ahead and say console.log element ref dot current right now this pay close attention to this this is super important you know that use effect hook runs after the component has mounted and the browser has painted it on the screen right we know that that means this particular thing means that when the component mounting process and everything is done what will happen is that this riff attribute will set the current value of this particular ref as this html div element so what you can expect to see ref element right here is that this should contain your div element so let's just go ahead and refresh this and let's see so you can see this riff element is directly this div right here however pay close attention to how this operates so let's just go ahead and for example i have something like you know on click i say set counter value value plus one right so we are back to where we were and now i have i am talking as the p tag so i just say that hey if value modulo 2 is zero that means on even numbers i want to show it and on all numbers i want to hide it and if i give a ref to this p element what do you think the console logs would look like let's see so i'm going to go ahead and refresh this and i think we have an error set counter yep this is not value this is actually counter right so let's refresh this and now you can see we have a ref which is completely fine because this p tag is in fact available on the page but when you click on this you see the ref element is null right so you have to be careful when you're trying to access element.if dot current dot you know for example element ref.current dot tag name right so if you're doing something like this if you refresh this you're gonna see the first time you get the correct tag name but the next time there is an error so you have to be careful that this could be null if the element is not mounted on the page right this is important with that being said the usref thing does not has a callback just like we discussed in the last video this does not has a callback inside it which triggers whenever the current property is set right we talked about this in the last video as well there are used call back riff and all that stuff there are external hooks but the internal hook which comes does not come with a callback right so this is just a sort of a free floating object with a current property which is mutable and every time a re-render happens it's gonna assign that particular current property if you are supplying this other ref to some element to that particular html element itself right but you if you know that the element will not be hidden or you know will not be just going away randomly then you can of course very conflict confidently have a inner text or inner html or you know whatever you want to do it will just work absolutely fine right so that's how you make use of user if as a second thing as well another interesting use case of user f is that you can pretty much just go ahead and have a use ref of something like you know renders for example and you initialize it with zero right and on every single render you say renders dot current is plus equal to 1 because we know that this has a mutable value that is it will not trigger any state updates not trigger the re-renders so you can do something like h2 current renders and render start current right so you can do something like this just to track just to keep a track of how many renders you have already done now now this is an interesting part you see that actually the value right now is one the current renders value right now is one because we know that use effect runs after the rendering is done but we still see zero because you know once we set this to one there is no update to update the ui so to actually uh you know just to make more sense of the data and keep it real rather you should do a plus one to it so now if you refresh this you have current windows 1 which is the initial render then if you click on you know if you do any sort of render it'll just update the counter and if there is any other re-enter for example from some component or for example if the parent props changes or anything happens this current re-render would update automatically but i hope you understand why i put a plus one here and why on the initial boot uh this actually showed zero initially if there is not plus one here right if you do not understand that i would highly highly recommend you to watch this video and a couple of videos about use ref again so yeah we discussed this in a great depth in the previous video as well if you skip that so yeah that's pretty much it for use ref i think we have covered a lot of stuff a lot of ground along the way and i hope this puts things in perspective in the next video i'm gonna show you a way how the use state can act similar to how user if looks like so that is all for this one i'm gonna see you in the next video really soon hey everyone welcome back and in this video let's just go ahead and take a look at how you can make or make use of you state as a use ref thing right so let's see let's say i want to make use of the surrenders thing again so what i can do is because you know i know that user f would create an object like this and now this object is um you know same on every render this these two things are important right the current property is not so important just given the fact that this is not being monitored so what you can do is you can have a renders which is a u state and the state is current with zero and then you do a zero right here let me just tell you what happened here so this renders and this renders right here is similar right so i can pretty much replace this renders like this comment this out and if we take a look refresh if i click on this you're gonna see it works pretty much in a similar way just like user f worked so what's happening what the hell is happening here let's take a look at that so you see that use state will actually return you two values right the first value is the set the getter right and the second value is the setter so the getter in this case would be an object with a current of zero right you're gonna get an object whenever you do for example r set r something like this then the r is this object and the setter will be a function which will allow you to update the whole object itself right instead of this object if you want something else you can place that but if you just pick up the getter you lose the setter along the way that means you're not using the setter at all so it's it's like saying something like this and then never using set r right so instead of doing something like this i just did render and i selected the zeroth element which is just our getter element right so once i did that i have this object with me now remember remember remember remember that you can only modify your state with the setter object that means react will only trigger a re-render when you call the setter object of the you state hook it will not trigger a re-render if you try to modify manipulate um the state directly right because it just doesn't know it just doesn't care that you are mutating the state right because every time you call this set a function then it's going to run the new occurrence of that app function you know just like we discussed how it calls it again and then it is going to re-render all the stuff but in this case we just lose the setter that means this value will never update and because this is an object react will always keep on returning you the same object from the u state because that was the original value right and you can mutate and play around within this object if you want right in fact you can just keep you know a bunch of properties bunch of more properties prop 1 as 100 prop 2 has 200 and then you can pretty much just you know do a prop 1 as plus times equal to stuff like this and you can make use of this if you want to right again similar difference why would you want to do this and not something like uh this the reason is you do not want to value the global scope because this will not be cleaned from the memory if the component unmounts right but the state variables the refs and everything will be cleaned automatically for you you don't have to do them so yeah that is another way of using the mutable feature of refs through u-state you should not probably use this you can pretty much just stick to use ref only if you want to but you should know that this is possible right so yeah that's pretty much it for this video hope you learned something new i'm gonna see you in the next one really soon hey everyone thank you so much for watching the free preview of advanced react hooks concepts if you want to continue watching reuse reducer use memo use imperative handle you know use callback all those kinds of hooks with creating your own custom hooks and creating a few applications around it make sure you are a code damn lead member and you're gonna have access to the whole learning path of react which consists of all the topics which i mentioned alongside with the advanced react patterns very very soon the courses are coming and by the time you are watching this video chances are they are probably live on the website with all the videos done so if you are elite member you can have a discount link is in the description you can go ahead and watch the complete courses not only the courses but you can practice hands-on with the projects as well and everything you're gonna find are linked as courses in these topic breakdowns so once again thank you so much for watching the course if this helped you if this if you enjoyed it don't forget to leave your comment and let me know how this helped you and if you want the full preview if you want the full course feel free to go to codename.com practice learn do whatever you want to do with your knowledge so that is all for this video i'm gonna see you in the next one really soon [Music] you
Info
Channel: codedamn
Views: 12,125
Rating: 4.8418603 out of 5
Keywords:
Id: 324czHa9O9U
Channel Id: undefined
Length: 102min 9sec (6129 seconds)
Published: Tue Jan 26 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.