Learn React Hooks: useCallback - Simply Explained!

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's up guys Darius cousin here welcome to the last used callback tutorial you're ever gonna have to watch let's get into it alright cool so let's talk about use callback Muse callback is a hook that comes pre-built from react but it's not a hook that you're going to use all the time you're certainly not going to use it as often as use effect or you state for example but I can guarantee you that you will use it and the times that you're going to use it it's going to be very impactful for your performance it can sometimes make or break your application in terms of performance so it's very important make sure to watch until the end because we're going to cover some very crucial topics to use callback so I have here a very simple application you can see it here on the right we have a list of users we have a button to shuffle and an input to search for the users the code looks like this we have our list of users here right it's state we're going to use you state then we have this handle search function which all it does is it takes this list of users which is the hard-coded list of users which is also what we give to the state to initialize or state users we take this list we filter it and then based off this text here we're only going to return the user if it includes the text essentially this is the feature right here you type something Alex it's going to return only the users that have Alex in the name this is pretty straightforward it sets the users with this um use state right here then this handle search function is being passed to the search component right here which for now we're going to look at it in just a moment but ignore it for now then we have this Shuffle button which all it does is it just sets the user to shuffle Shuffle don't worry about it it's just a function that just shuffles the array around and you can see it right here it just puts a different order to the users we're going to use this to show you how this can impact the performance of your application and finally we are mapping over the list of users right so pretty simple there's not that much to it this is what we're working with cool so now let's open up this search input component and see what this is this as you can see is a pretty simple component there's not that much more to it it doesn't even have its own state it just takes in an unchange function from the parent which has a text parameter and then it renders an input with a placeholder and then calls this on change with the event and passes the value of the event to it right very very simple what I want you to look at is that it has demo here it is exported wrapped in memo memo is not the topic of this video but it is important to mention it because it kind of affects use callback memo is a hook that is also used for performance reasons and what it does is it wraps the component that you're trying to export in this case search and it intercepts the render of this component and it checks if the props are different from one render to the next so what I will do is it will take the props of the search component which in our case is just the on change and it will check if the on change prop is different from the previous render to this render if it is it's going to re-render the component if it isn't it's going to skip rendering the component this is something that you use for performance because some components you don't want to re-render them unless some of the props changes and this is very important right so if this on change is different this is going to be re-rendered if it's not different it's not going to be rendered so actually to see this we're going to add a console log to the search opponent to indicate to us when this component is going to be re-rendered and when it isn't so let's do that I'm going to do console.log and I'm going to say search rendered great make a bit of space here right then we're going to go here open up our console go to console clear everything and refresh and see what happens so this is the first render of our component you're going to see here that search is rendered right which makes sense right this search here which has this input is rendered it has to render at least once that is how it works if it didn't render we wouldn't see the search input right here now let's see what happens if I press this Shuffle button right here we've seen that this Shuffle button what it does is it'll Shuffle this array of users and put them in a random order but is it going to re-render our search component right I'll let you think about this for just a few seconds before I press it because it's not obvious right I mean we did wrap this with use memo so it shouldn't we render unless the props are different so is it going to be render well let's see I'm going to press Shuffle our users are shuffled but the search rendered which is strange right I press Shuffle again their search re-rendered again why is this well let's look at our code for a second right all that we really have is this handle search function right that's the only props that is being passed to search and search is wrapped with memo so technically it shouldn't we render right because nothing really changed or did it see this is the important part we have to look at this handle search function because this is where the problem is it's very important to know and understand that in react functions are different on every render by default it's not that the contents of the functions are different right this function doesn't change right it's running the same code every time there's nothing in it that changes it doesn't even use the user's State variable which could change right it uses this hard-coded all users variable which is static this will never change across we renders but in react functions even if they have the same code even if they're doing the same thing they are going to be considered different on every render which means if you do function equals equals equals function it's going to return false it's not going to return true even if the function is the same and does the same thing so then when you think about search right our search component here which receives this handle search function on change and then as we've seen it has this memo here memo what we'll do is it will go and check from the previous render this on change function and then it will check is it equal or is it not equal to the new on change function of this render and since in react functions are different on every render by default that equality is going to be false which means that the search is going to be re-rendered so that's exactly what we see here right we click Shuffle it is re-rendered we click Shuffle it is re-rendered because the on change function this handle search function is different across V renders so that is our problem that is that the performance problem that we have because in this case search is small right it's just rendering a component so we don't really care about the fact that this is being re-rendered but you can imagine that if you had a bigger component that did a lot more things maybe had some code in there that was super expensive to run or if that component rendered many sub-components that each did their own thing the sum of that could be very expensive and you don't want to re-render this all the time when it's not needed right because I mean if you look here do we really need to re-render the search because all we're doing is we're shuffling the users the only area of concern that we have is this user's array right here we don't care about the search the search does nothing to the users it doesn't receive the user's estate it doesn't even manipulate the users on state which is very important because although this handles search function will manipulate the users from the searches perspective it doesn't know what the function does all it knows is that it receives an on change function and it should call it with some text and then this function will return nothing it doesn't know about the inner workings of the actual own change function and that's good because that's the way it should be this component is what you would call a dumb component it shouldn't be aware of what the parent does it doesn't need to all it needs to know is that it has an input and on change it will call whatever the parent gives it with the value of the event so when you look at all of that then search doesn't need to be be rendered when this Shuffle button is pressed so that is our problem so now how do we fix it well that's the whole point of this video we're going to use use callback to fix it use callback is a hook that is meant to be specifically used for this purpose what it does is it it'll wrap your function and return to you a new function that is memoized which means that is frozen that will be identical across renders we're going to use this wrap this whole thing with use callback and you'll see how this will fix our problem so let's do that let's go and import use callback from react then we are going to copy this entire thing and then we're going to do use callback open a parenthesis paste this entire thing and then we're just going to go at the end and add the dependency array and then we are going to save what use callback does is it takes a function in this case it is this function right here which is the same one that we had before it wraps it and then it returns to a new value that is identical and then as the second parameter you can provide the dependency array which allows you to control when this function should be different so now our handle search is again it's a function it does the same thing it runs the same code but it is memoized it is frozen in time it'll be the same identical across renders so now let's look at what happens when we save this and then if we refresh and then we press the shuffle button again we still have this search here that rendered once right because again this component has to render at least once and now if I press Shuffle nothing is being locked I press Shuffle again nothing is being logged right which is what we want this is how use callback works this function is identical across V renders which means that our search component is going to look through this memo here it's going to look at on change from the previous render compared to the one from this render and it's going to see that they are identical so there's no need to re-render this component again cool so with this we've now effectively solved our problem we've managed to use use callback for what it's used for and prevent an unnecessary render and our application is now performant obviously again this is a super simple example so the performance is really unnoticeable but if you had a large example with many components this would be very important now before we finish this tutorial I want to show you something that you have to be very careful with when using use callback because if you're not careful and you do this incorrectly you're gonna get some bugs in your application and you're not going to understand what happened or really what is going on so let's say that instead of just filtering the users I also want to log the first user in our list right that's the user right here I want to just log this to the console before doing any filtering so let's do that let's put a console log and then we're going to do users zero right that that's going to without the zero that's going to log the first user in our array so let's do that now we have a console here nothing locked because this is on the search right so whenever this search is called it's going to log the first user and it's going to put it here in the console so what's going to happen if I start to press um a right I want to press a to filter for Alex but this is going to run this console log is going to run before we filter the users so what really we should have in this console is we should have John right because John is the first user this code is going to come it's going to log it and then it's going to filter the users so let's type A and see what we get to our console a we get John as we expect right John was the first user this code came logged it there's no problem there but now what if I press L to continue filtering for Alex right we should now have Alex that locks because at this point in time Alex is the first user and what this code should do is it should lock Alex because it is our first user before filtering the other users so let's type L and see what we get we Type L and we have John again why because Alex was the first user John isn't even in the list anymore so where did this get John from well this is the important thing that you absolutely have to understand with use callback using use callback is going to memorize the function which we've said is going to freeze the function in time but that also means that it's going to freeze everything in the function at a certain point in time in our case it's going to freeze it on the first render right so on the first render we had John here that was our first user in the array so when we type A it logs John as expected but that function is still frozen so from the point of view of the function users still contains John so even if I put l again it's still going to log John because users is Frozen at a specific point in time this is how use callback works and it's very important to not to fall into this when using it because you're going to get some unexpected behaviors and as you can see some obvious bugs so how do we fix this well that's where the dependency array comes into play this little array right here I've said that we're going to use this array to control when this function should be different because we don't want to freeze it forever all the time we want to control it and only change it only update it when we want and if we look at this dependency array right here you're going to see that vs code is being very helpful and it's telling us that use callback has a missing dependent NC users right because it's looking at our code it's smart enough to go and look at our code and say hey you're using users in this function are you sure you don't want to put this in this dependency array because if you don't you're gonna get some unexpected behaviors which is what we've been getting right and if you think about this from a logical perspective we want this handle search to be different whenever users changes because we are logging the users the first user so we want access to the most up-to-date users array so that we can lock the most up-to-date user right so what we're going to do now is we're going to add users to this array and then with this we are going to save and then we are going to refresh and then we're going to see how this behaves now so let's type A again and see what is locked we're going to have a and then you see that John is still locked which is fine that is what we expect right John was the first user before we filtered then we have this search rendered which again is normal because now we've given it users as the dependency array users is no different it has updated values and so this handle function is going to be different which is going to cause this memo to consider it different from the previous render and re-render this search component so this is totally what we expect now if we Type L let's see what we get we Type L and now we have Alex which is the correct value because Alex was the first element in in the array before we filter it and then our search has to be rendered this is how use callback is meant to be used you're not supposed to freeze your function every time forever that's not the way to approach this in some cases in some very rare cases that is the approach to do but oftentimes if you're doing stuff with values you're going to want to put them in the dependency array to always get the up-to-date values now this is still performant the still fixes are problem or for performance it's not because we have users here that it changes that now we get the search that is we rendered which is what we try to prevent in the first place although that happened and we kind of did undo what we've tried to do in the first place you can imagine that if we had a different piece of State here whatever it would be and that's some other part of the component would update that piece of state it would not change users and so it would not change this handle search function and thus cause the search to be re-rendered it's only happening now because we're dealing with the users directly we've still solved our problem for everything else except users which is what we want because we want to control when this is re-rendered and when it's not and that is what you have to understand about this callback you should never freeze your functions forever you should only freeze them until it's absolutely necessary and until you want them to change so really keep this in mind and really try to wrap your head around use callback because that is the way that it was designed to be used so there you go that was his callback I hope that by now you're able to go out and implement this and I would actually strongly recommend that you do that work with it play with it add some console logs here and there because it's very important that you understand how this works fundamentally because you're going to have to use it in your applications and you're going to have to understand how it is used if you've enjoyed this video make sure to leave a like and also subscribe because I'm going to be posting a lot more of these types of content and it really has helped me out a lot it shows me that you enjoy and that you want more of these so please do that and yeah my name has been deris cousin this is causing Solutions and I will see you all in the next tutorial ciao
Info
Channel: Cosden Solutions
Views: 28,871
Rating: undefined out of 5
Keywords: react tutorial, react crash course, react developer, learn react, react hook, react hooks, react hooks tutorial, programming tutorial, react hooks explained, computer science, tutorial for beginners, react component, learn programming, web development, frontend development, coding for beginners, simple code, easy programming, useCallback hook, useCallback tutorial
Id: MxIPQZ64x0I
Channel Id: undefined
Length: 17min 14sec (1034 seconds)
Published: Sun May 14 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.