useCallback STOPS this React MISTAKE | useCallback React Hooks Tutorial

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
that is a lot of red and a message you don't want to see we've got an endless rendering loop [Music] hello and welcome hi i'm dave today we're going to look at the react hook use callback the key to understanding this hook and how you can avoid the common re-rendering loop mistake you saw at the beginning of this video let's get started by looking at the key to understanding use callback and the key to understanding this concept is referential equality so i'm going to use the console over here on the right from chrome and then on the left we've got visual studio code but i'm just going to drag the console over because it's going to be the main focus here at first so i'm going to type in the number 7 which is a primitive value and use strict equals 2 7 and that's true likewise if i type in a string use strict equals type in the same string that's true that's not true in javascript though when it comes to objects so if i do the same with an empty object we get faults it occupies a different space in memory it looks the same but it is not the same it does not have referential equality the same applies to arrays they are both of course type of object in javascript so we've got a couple of falses there and we've confirmed that even though an object looks like the other object it's not the same and the same for arrays well when it comes to functions that is our main concern with use callback use callback returns a memoized function it doesn't call the function it actually returns the definition so you can call that same function later so what we're concerned with is the referential equality i'm going to define a function here called ff as a factory function and it's going to return a function that simply returns my name dave from here i can say dave1 is equal to this factory function and i can say dave2 is equal to this factory function so if i were to call either one of these they would return my name the string dave however if i say dave1 is strict equals to dave 2 that's false and that's the key here because we need to understand that when react re-renders a component it recreates these functions and even though they look the same have the same name even the same definition both of these were created from the same factory function they're not the same they do not have referential equality this is where use callback can help us so now i'm going to drag this back over so we can see more visual studio code again and we're going to go to the react app a simple app that i have running that has a simple input here let's look at this i'm using some state for the user input and i'm actually displaying that output as well on the page so i could drag this down you can see the display there we don't really even need to just to see the display of that output because it's the same as what i would type in here but every time we update state as we know with use state it will re-render the component and then we have a sum function here and this sum function is grabbing num1 and num2 from state i don't even have the set state parts of you state in here because we're not using those we've just set these to 4 and 5 so they won't change on us but they are pieces of state and some is just adding them together and then we've got use effect here use effect is relying on the sum function it's in the dependency array so time the sum function changes use effect will run and i've just got use effect logging new sum and the value of the sum function so now that we've covered all of that let me start typing in the input over here in our app and i'll just type my name four letters dave and you can see four times in the console it logged new sum well sum we didn't really change it but it is a new sum function likewise the value was always nine nothing really changed so by re-rendering the component by updating state in something that didn't even play a role in sum we're creating a new sum and we're running this use effect that is looking for some to change and that's where we can really use some help from use callback to prevent that from happening because we don't want that to happen some shouldn't be re created just because we typed in our text input over here and of course it doesn't need to calculate a new value for us because it hasn't changed now let's add one more piece of state here i'm going to put it between the numbers and the user input and we'll just call this result and so this will have result and set result and i'll just set it to use state with an initial value of zero there we go okay so now we have our result and set result i saved that we got a warning because we're not using it yet and we got a warning about some as well and we can look at that in just a second too what i want to do is after we call some i also want to set the result here but i'm going to do it in a comment first and then we can actually look at that warning because that's important to see as well okay so i need to drag this up a little higher so we can read the warning better and what we get is a warning that pretty much says what i just went over besides the set result and result warning here so here we go line 9 11 where we have sum it says the sum function makes the dependencies of the use effect hook change on every render and that's because it's being recreated and it says move it inside the use effect callback so you could define some inside of use effect before you call it but then that doesn't make it as flexible you couldn't use it really anywhere else if you just defined it in here but it says alternatively wrap the definition of sum in its own use callback and so that's what we will be doing i'll clear this out for now so we can scroll this back down a little bit or pull it back down and i'll be able to type in the input again if we need to still got our console here but what i want to do inside this use effect now is set the result and this is a beginner mistake and it can easily happen because we usually want to set the state inside of a function we're looking for something to change then we're going to set that state but let me show you the problem i'm going to set it equal to whatever sum calculates we're depending on sum now this returns a primitive value and our numbers never changing it's always going to be 9 when we call sum we're not updating this state at all for num1 or num2 so we're going to get lucky here just because react is smart enough to say hey this is the same value and it's a primitive value so i'm going to save and now notice we got new sum value nine and it only happened twice but really if we think about this logic it should be an endless loop and that is because we updated the state when we update the state the component re-renders when the component re-renders it creates a new sum when some changes it calls use effect use effect we're updating the state inside of this use effect that sounds like an endless loop so why didn't we get one well it's because you state is smart enough to say okay i'm getting the same primitive value the number nine and i've already got the number nine so i don't need to continually update it so it happens it runs this use effect at load time and then it updates the state and happens one more time and after that it goes now i've got the same value i don't need to keep doing that and it's really preventing us from a big mistake here which would be an endless loop so let's go ahead and fix this now and we won't see these issues anymore or at least this about the use effect hook here let's see if we still have a warning about result just because we're not using it anywhere in the app right now but let's go ahead and pull in use call back up here at the top and now we can wrap our function and use callback so we'll put it right outside the function definition we'll put a parenthesis at the end but we also need a comma here because use callback has a dependency array just like use effect and you can tell we're dependent on the state num1 and num2 so we need to put those in the use callback dependency array and if i drag this just a little more we can see it's not wrapping now so there's our full used callback now we could put this on separate lines as well just like we would with any other function but this works right now so we've got our function here as normal but we've also got the dependency array and it's wrapped in use callback what use callback does is memoize the function so now it will have referential equality so i'll save this and we'll come back to our application and we can see what warnings we're getting and i believe we're only going to be getting a warning for result and that is correct and we only got new sum value 9 once now here's the real test i'll clear this out so we have more room and i'll type now let's see how often this new sum value gets logged to the console it's not getting logged to the console at all because sum is not changing when we update the state we're re-rendering still because we're updating the user input state over here but we're not creating a new sum function it's memoized and that is really when we want to use use callback if we have our function in a dependency array and if that hook whatever hook has the it doesn't just have to be use effect but whatever hook has the dependency array we'll be looking for a change of that function well then we need to wrap it and use callback now we might also need to wrap a function and use callback if we were passing it down as a prop and the component we were passing it to is memoized because if we didn't wrap it and use callback and we kept sending a new function it would break that memoization as well that could be in a tutorial on react dot memo but the main reason you usually see use callback used is because a function is going into a dependency array like we see here so with that said let's look at what does create the endless loop that we saw at the beginning of this tutorial okay i'm going to create another function and i'm just going to call this function build array and this function is just going to take those two pieces of state again and make a new array with them num1 and num2 and really that's all it's going to do so we're building an array so now i'm going to use this build array function in place of sum and i should be able to select both there we go and replace both of those and now we'll say new array and we don't really need value here we'll just say what the array is oops i can't type there we go and so now we could just call build array right here as well so i guess i could have replaced that but i'll just type it out build array inside use effect now i'm going to type comment out the set result again so we don't have an issue at first but we can see what happens here so save this much you can see we've got new array four and five but once again i believe we're still going to have that warning that we had before this is not wrapped in a used callback so yes we've got the same message about either put build array inside the use effect and that means put the definition inside use effect or alternatively wrap it in use callback which is once again what we'll do i'll clear this out though and i'll just delete my name we can see once again for every backspace i hit or for every letter i type it logs to the console new array and then of course it's also outputting the array here but we have a bigger issue because remember an array is not a primitive data type so react will not save us from ourselves and this is where i see beginners have lots of problems with this because once again they set the state and they have a function in the dependency that is recreated on every render well when this happens this will create an endless rendering loop so i'm going to go ahead and do this and it may crash everything for me but we'll see what happens now so i'm going to save and there we go endless rendering over here on the right and i'll scroll this up that is a lot of red and a message you don't want to see we've got an endless rendering loop okay i'm going to stop the app open up the terminal and hit control c there we go so the app is stopped and now i'm going to go ahead and close this react app and i'll have to restart it after we fix this issue so close out of the terminal for now and clear this terminal window as well but we'll launch a new one over here so what we need to do is once again apply use callbacks so we have use callback and we're going to wrap our build array function and now inside we once again need to provide that dependency array which has num1 and num2 for use callback i can drag this over just a little more so we can see it on one line for now and so now we've applied use callback to the build array and so now it should have referential equality and we should not see that endless loop issue when we set the build array result as the result here so let's go ahead and save all of our changes now i'll drag this back over so we can see the new app launch control back tick or the terminal menu will let you open a new terminal either way npm start for your react app and it should launch a new tab over here for us and once we do that we'll of course have to open up the dev tools as well okay we've got the app open i will open the dev tools now in the console we've got a warning for result and a warning for some because we're not using some now but what we don't have is any endless loop or any problem there and that's because we used callback to memoize our build array function so once again even when i type we are no longer outputting new array to the console so i hope these examples and they are simple examples but i hope they have given you a better understanding of why we use callback and especially the key referential equality and that will help you understand not only use callback but other react optimizations as you learn about them remember to keep striving for progress over perfection and a little progress every day will go a very long way please give this video a like if it's helped you and thank you for watching and subscribing you're helping my channel grow have a great day and let's write more code together very soon
Info
Channel: Dave Gray
Views: 1,102
Rating: undefined out of 5
Keywords: usecallback react hooks, usecallback, react usecallback, usecallback hook, react hooks, react hook, react hooks tutorial, react tutorial, usecallback example, usecallback examples, react mistake, react mistakes, usecallback react hooks example, usecallback react hooks code step by step, react js usecallback, reactjs usecallback, usecallback tutorial, how to usecallback, usecallback how to, usecallback mistakes, tutorial usecallback, referential equality, javascript, js, react
Id: FB_kOSHk1DM
Channel Id: undefined
Length: 16min 14sec (974 seconds)
Published: Fri Nov 19 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.