useCallback is a React Hook that can provide referential equality for created inside your functional React components. In this tutorial, you will learn all about referential equality as well as when and how to apply the React hook useCallback. Just starting with React? I suggest starting with my full 9 hour React tutorial course here: ua-cam.com/video/RVFAyFWO4go/v-deo.html
It is the best explanation of React hooks I've ever seen on UA-cam. Thank you, Dave! Starting from the very first step, you highlight the key elements of the issue and describe how it can be resolved.
I love your way of explaining things Dave. I am following a React course on Udemy, and i always end up at your channel to get a better understanding of al the React topics. Your explanation is just simple, and your not "over" explaining things. Thanks, and keep up making this valuable content!
About time. I actually came for a refresher after watching your other videos. Your Redux Toolik playlist is what introduced me to your channel. Thanks to that I have implemented RTK Query instead of using Axios interceptors for a project I am currently working on. keep it up
Wonderful topic treated by a wonderful teacher. All these years I have remained a beginner until I came across your channel and I am very excited about stepping up my skill set to advanced react developer 😎
Interesting, especially for me who does not even know exactly what triggers a re-render of a component. So much to learn.. Thank you for another good video.
Thanks Dave, that was very helpful, One must learn about react component lifecycle in order to not fall into such mistake, BTW, Congrats for the 10K+ subs and hope to reach 100K soon 💯🎉
Ahmad, thank you my friend! Yes, with React moving to functional components and hooks, the stages of the component lifecycle are not as clear for some as they were with classes when we used to reference shouldComponentUpdate and other methods in the lifecycle. I do really like functional components and hooks better though. I appreciate your comments and thank you again for the encouragement and support! 💯🚀
@@DaveGrayTeachesCode Although it's a little, I'm just trying to give you back some of what you've given us, I learned a lot from you, so thanks to you my friend
Yoooo you better start your udemy course I ll be the first one to pay😂. Your explanation was perfect and you know how to explain the concepts perfectly with good examples.
Great video Dave 💯🙏, Doubt: at 8:00 , "it happens one more time" .... Is that once on first render logs once and then after setting state again ? Confused on second time log here ... By the first time it gets same value and second time it shouldn't be logging right or 😖🙆 ...
useEffect always runs once when the component loads. It then checks the dependency array to see if anything has changed. In the spot you mention, React is "saving" us from an endless loop because the function "sum" is re-created every render.. which means it has changed.
Thanks for the clear video! I am still a bit uncertain when we need to use a function in the dependency of useEffect. For the example (14:30), it seems we can just put [num1, num2] as dependency of useEffect directly without using useCallback.
A function defined inside the component (but outside of useEffect) will always be re-created when the component is re-rendered. To prevent that, you can apply useCallback. You need to use a function in the dependency array of useEffect if you are calling that function inside of useEffect AND you did not define the function inside of useEffect. setState is the only exception to this.
Thanks for that, so basically only time to use useCallback is when you put the function name within the useEffect dependency, other than that you don't need it? In some code at work we have a use effect with [] as the dependency, and in that useEffect it sets up a onClick listener and assigns a function to the onClick, that function is within a useCallback -- this that right? (Also have the clean up for removing the onClick listen too)
Dave, with your wealth of experience. I would like to request a video series on the journey of a front end engineer across World(India) . The roles available( fresher, senior, architect, remote work, work from home, etc) expectations and interview preps ( who is a good fit for this role, when should one consider upgrade or switching to a new company) and how much time needs to be dedicated, how to make a killer resume, etc etc. I am sure plenty often think if they could do better than their current role, could be in terms of money or job satisfaction
Thank you for the request. I enjoy creating coding videos but there are some great channels for the content in your request. I recommend Danny Thompson's channel and Twitter feed. 💯
Earned a subscriber today, great video. Question: If you defined your function in an external file and imported it, then you wouldn't need to use useCallback in this scenario? Or am I missing something.
Good question - useCallback is used for functions defined inside the functional component. If you import a function from an external file, it will not be re-created on each render. However, a function defined inside a functional component will be re-created on each render - unless it is memoized with useCallback.
Dave, can you explain to me, why you add the function as a dependence in the useEffect? I don't dever see this case, usually it is props or state items.
useEffect looks at the dependencies in its array, and if one changes, it runs the code inside. If we did not apply useCallback to the function buildArray, it would be re-created every time the component renders. And that means it would be a new function every render which in turn would cause useEffect to run. We know the code doesn't change, but JS doesn't know that. It just creates the function again. This is the point of useCallback. You can memoize a function with it so it is not re-created with every render. useEffect will still want the function listed in its dependencies because we use it inside of useEffect. I hope that helps! 🚀
Thanks for tutorial Dave! Correct me if I am wrong, if we do not pass function in dependency array, we don't need to memoize it (there is no reason) or is it still an overhead for performance to constantly recreate those function everytime? Don't feel like wrapping every function inside component is correct approach.
Great question! A function could also be a dependency if it is passed down to a component as a prop. We can memoize those child components with React.memo(), but if they receive a new function every time it will break the memoization. I can make a separate tutorial on React.memo(), too. That said, small anonymous click handlers and other functions that are not passed as dependencies anywhere else do not necessarily need to be put inside of useCallback(). There is some debate here and approaches vary. I agree that not every function needs to be (or should be) inside of useCallback(). useCallback is another function that creates its own overhead, too. Sometimes the small gain is not worth the cost of adding another function. Deep dive on this topic in this article by Kent C. Dodds: kentcdodds.com/blog/usememo-and-usecallback
Hi Dave , Just a basic question, i did not see those specific warnings about usecallback & sum in my console, i used your same example but with vite set up.Do we need to do some config changes wrt to vite to see those warnings in console ?
This tutorial used React 17. You can check the source code link in the description. Look at the package.json file. You can install the version of React I used to get the warnings that React 17 provided.
Going to recommend watching again because that is the core concept here and why useCallback exists. If you define a function inside the functional component, it is re-created on every render. If you try to list that function inside the dependency array of useEffect, you will create an infinite render loop - because the function you just defined changes on every render - and every time a dependency changes in the useEffect dependency array it triggers another render. To avoid re-creating the function on each render, you can memoize it with the useCallback hook. Even if not using the function in the useEffect dependency array, do you need to recreate it every time? Probably not. useCallback may therefore improve efficiency. Some devs use it all the time and some do not. This is a debated topic.
why is if i didint call sum() in console in useEffect but have sum as dependency. useEffect(() => { console.log("sum is"); }, [sum]); changing in state of setUserInput still call useEffect and console too. cause i didint call the sum() function there. i didnt understand that. my guess is that when change in state give new reference to sum(), thats why it behave in this way . please help me
I don't fully understand your question, but in general, every render of a component will redefine a function that is created within the component - unless you apply useCallback.
The answer to this is situational. If it is a function that fetches data and you want to call it every time the component is mounted, you could just define the function inside of useEffect and call it there. The useEffect dependency array should be empty so it is only called when the component is mounted. However, if you are defining this function outside of useEffect, then yes, you likely should put it inside of useCallback or the function will be re-created on every render of the component.
I might be a noob in React but can anyone explain why we would ever use a function as dependency in userEffect? Would we wait for anyone to change that function definition then we will run our logic inside useEffect? Thanks.
If you do not define the function inside of useEffect, you will receive a warning about missing dependencies. Also, the functions outside of useEffect are re-created every render. The way to avoid this re-creation is with useCallback. The way to avoid that is defining the function inside of useEffect when possible.
why wouldn't you put either, [num1, num2] (only re-run when the numbers being summed change) or [sum()] (only re-run when the actual sum returned changed) as your dependency array? that way you aren't relying on a function ref for dependency. also, useEffect isn't really a good place for this kind of code. it's better to place that into event handlers. useEffect should really only be for synchronization tasks. useCallback is really only important when you are passing a function as a prop to another component. if you are doing this, then useCallback prevents re-renders of the tree caused by referential changes of the prop.
Hi Matthew - these are just examples to explain to a beginner what useCallback is and what it does. Kind of like examples in a textbook. You can refactor them and work with it in different ways. Don't consider tutorial examples to be "production ready" or the only way. So the answer to your "why" question - I'm just providing examples while explaining what it is, what it does, and how it is different than useEffect for beginners to understand.
useCallback is a React Hook that can provide referential equality for created inside your functional React components. In this tutorial, you will learn all about referential equality as well as when and how to apply the React hook useCallback. Just starting with React? I suggest starting with my full 9 hour React tutorial course here: ua-cam.com/video/RVFAyFWO4go/v-deo.html
This is what a real tutorial should be like. Not just blindly copy/pasting code but explaining the inner workings of stuff. Thanks man!
Glad I could help, Ivan! 💯
@@DaveGrayTeachesCode this was a great explanation TBH
Amazing content! There isn't much advanced React content on UA-cam. So glad you make this one :)
You're welcome! 💯
It is the best explanation of React hooks I've ever seen on UA-cam. Thank you, Dave! Starting from the very first step, you highlight the key elements of the issue and describe how it can be resolved.
I'm glad it helped! You're welcome!
I am new to react. And I was struggling to fix this maximum depth exceeded errors. Now I got a clear idea on how to fix them. Thanks
I love your way of explaining things Dave. I am following a React course on Udemy, and i always end up at your channel to get a better understanding of al the React topics. Your explanation is just simple, and your not "over" explaining things. Thanks, and keep up making this valuable content!
Thank you! 💯
Wow! The expiations open my eys to understand how the sum functions are created repeatedly. Awesome!
I really wish I had found an instructor like you earlier!
About time. I actually came for a refresher after watching your other videos. Your Redux Toolik playlist is what introduced me to your channel. Thanks to that I have implemented RTK Query instead of using Axios interceptors for a project I am currently working on. keep it up
Glad I could help!
This is the clearest explanation video I have ever watched. Thanks
Glad it was helpful!
Wonderful topic treated by a wonderful teacher.
All these years I have remained a beginner until I came across your channel and I am very excited about stepping up my skill set to advanced react developer 😎
Glad to hear I have helped you!
for that van helen signature guitar, I should have known from the beginning that your content is gold.
Thank you! 🤘🎸
Interesting, especially for me who does not even know exactly what triggers a re-render of a component. So much to learn.. Thank you for another good video.
Glad I could help, Ben! Updating state will trigger a re-render of a component and child components if they also depend on that state. 💯
Thank you Dave I really appriciate this content.
My favorite web dev instructor
Thank you!
I'm so glad I found your channel. I really appreciate the great tutorials. Thank you!
You're welcome!
you are incredible. I am grateful that I found your channel
Glad you are here!
Thanks Dave, that was very helpful,
One must learn about react component lifecycle in order to not fall into such mistake,
BTW, Congrats for the 10K+ subs and hope to reach 100K soon 💯🎉
Ahmad, thank you my friend! Yes, with React moving to functional components and hooks, the stages of the component lifecycle are not as clear for some as they were with classes when we used to reference shouldComponentUpdate and other methods in the lifecycle. I do really like functional components and hooks better though. I appreciate your comments and thank you again for the encouragement and support! 💯🚀
@@DaveGrayTeachesCode Although it's a little, I'm just trying to give you back some of what you've given us,
I learned a lot from you, so thanks to you my friend
Thanks Dave, this gave me detailed knowledge about useCallback hook.
Glad it was helpful! 💯
You are a very good teacher Dave. Appreciate your work. Kudos
Thank you for the kind words! 🙏🙏
Yoooo you better start your udemy course I ll be the first one to pay😂. Your explanation was perfect and you know how to explain the concepts perfectly with good examples.
Thank you! I may not put one on Udemy, but I do plan to offer a course yet.
That's what I need, Thank you! the screen view is big for me easy to see Chrome dev tool. :D
Great video Dave 💯🙏,
Doubt: at 8:00 , "it happens one more time" .... Is that once on first render logs once and then after setting state again ?
Confused on second time log here ... By the first time it gets same value and second time it shouldn't be logging right or 😖🙆 ...
useEffect always runs once when the component loads. It then checks the dependency array to see if anything has changed. In the spot you mention, React is "saving" us from an endless loop because the function "sum" is re-created every render.. which means it has changed.
@@DaveGrayTeachesCode Ah Thanks alot Dave, how on earth I missed your videos 🤪 ....
Thanks for the clear video! I am still a bit uncertain when we need to use a function in the dependency of useEffect. For the example (14:30), it seems we can just put [num1, num2] as dependency of useEffect directly without using useCallback.
A function defined inside the component (but outside of useEffect) will always be re-created when the component is re-rendered. To prevent that, you can apply useCallback. You need to use a function in the dependency array of useEffect if you are calling that function inside of useEffect AND you did not define the function inside of useEffect. setState is the only exception to this.
@@DaveGrayTeachesCode I see! Thanks! No wonder useEffect often defines a function directly inside it.
@@DaveGrayTeachesCode I saw some people put [dispatch] in the dependency of useEffect. Is it necessary if they use dispatch inside useEffect?
@@jiweihe3413 dispatch won't change but the linter will give a warning if you don't include it in the dependency array.
Crystal clear explanation. Thank you so much sir ❤️
You're most welcome!
THANKS A LOT!!! Perfect explanation! 😍
Welcome! 💯🚀
Fanstastic explanation. Thanks
You're welcome!
Thanks Dave.
you earned yourself a subscriber, this is the perfect explanation
Glad I could help, Ratan! Welcome!
Great Tutorial.Thanks a lot 😇
Glad it was helpful!
awesome video Dave,, thank you so much
You're welcome!
Very helpful tips, thank you!
You're welcome!
Great tut. Thanks
You're welcome!
Excellent content! 👏👏
Thank you Aman! 🙏💯
Thanks for that, so basically only time to use useCallback is when you put the function name within the useEffect dependency, other than that you don't need it?
In some code at work we have a use effect with [] as the dependency, and in that useEffect it sets up a onClick listener and assigns a function to the onClick, that function is within a useCallback -- this that right? (Also have the clean up for removing the onClick listen too)
Dave, with your wealth of experience. I would like to request a video series on the journey of a front end engineer across World(India) . The roles available( fresher, senior, architect, remote work, work from home, etc) expectations and interview preps ( who is a good fit for this role, when should one consider upgrade or switching to a new company) and how much time needs to be dedicated, how to make a killer resume, etc etc. I am sure plenty often think if they could do better than their current role, could be in terms of money or job satisfaction
Thank you for the request. I enjoy creating coding videos but there are some great channels for the content in your request. I recommend Danny Thompson's channel and Twitter feed. 💯
@@DaveGrayTeachesCode thank you
Great teaching skill. Thank you Sir. 👍
You're welcome! 🙏🙏
Earned a subscriber today, great video.
Question: If you defined your function in an external file and imported it, then you wouldn't need to use useCallback in this scenario? Or am I missing something.
Good question - useCallback is used for functions defined inside the functional component. If you import a function from an external file, it will not be re-created on each render. However, a function defined inside a functional component will be re-created on each render - unless it is memoized with useCallback.
@@DaveGrayTeachesCode Thank you so much, much appreciated!
Thanks for this Gold lesson.❤
Glad it was helpful! 🚀
nicely explain thank you 😀
Glad I could help!
Thanks Dave 😀
You're welcome! 🙏
Great. Thanks.
Dave, can you explain to me, why you add the function as a dependence in the useEffect? I don't dever see this case, usually it is props or state items.
useEffect looks at the dependencies in its array, and if one changes, it runs the code inside. If we did not apply useCallback to the function buildArray, it would be re-created every time the component renders. And that means it would be a new function every render which in turn would cause useEffect to run. We know the code doesn't change, but JS doesn't know that. It just creates the function again. This is the point of useCallback. You can memoize a function with it so it is not re-created with every render. useEffect will still want the function listed in its dependencies because we use it inside of useEffect. I hope that helps! 🚀
what vs theme are you using? looks amazing
The GitHub theme 🚀
So good tutorial
Thank you, Sona! 💯
Thanks for tutorial Dave! Correct me if I am wrong, if we do not pass function in dependency array, we don't need to memoize it (there is no reason) or is it still an overhead for performance to constantly recreate those function everytime? Don't feel like wrapping every function inside component is correct approach.
Great question! A function could also be a dependency if it is passed down to a component as a prop. We can memoize those child components with React.memo(), but if they receive a new function every time it will break the memoization. I can make a separate tutorial on React.memo(), too. That said, small anonymous click handlers and other functions that are not passed as dependencies anywhere else do not necessarily need to be put inside of useCallback(). There is some debate here and approaches vary. I agree that not every function needs to be (or should be) inside of useCallback(). useCallback is another function that creates its own overhead, too. Sometimes the small gain is not worth the cost of adding another function. Deep dive on this topic in this article by Kent C. Dodds: kentcdodds.com/blog/usememo-and-usecallback
@@DaveGrayTeachesCode 🙏
Good video Dave. I learned the hard way why you shouldn't ignore those ESLint warnings in React. It wasn't fun 🤣
So true about ESLint warnings! Thanks for the kind words! 💯
Hi Dave , Just a basic question, i did not see those specific warnings about usecallback & sum in my console, i used your same example but with vite set up.Do we need to do some config changes wrt to vite to see those warnings in console ?
This tutorial used React 17. You can check the source code link in the description. Look at the package.json file. You can install the version of React I used to get the warnings that React 17 provided.
you are the best
شكرا
Why did we had infinite rendering. Can you please explain that part and how did you avoid that?
Going to recommend watching again because that is the core concept here and why useCallback exists. If you define a function inside the functional component, it is re-created on every render. If you try to list that function inside the dependency array of useEffect, you will create an infinite render loop - because the function you just defined changes on every render - and every time a dependency changes in the useEffect dependency array it triggers another render. To avoid re-creating the function on each render, you can memoize it with the useCallback hook. Even if not using the function in the useEffect dependency array, do you need to recreate it every time? Probably not. useCallback may therefore improve efficiency. Some devs use it all the time and some do not. This is a debated topic.
Thanks Dave!
damn your fun dude dave
Thank you Tommy! 🚀
This is really amazing! But laughing in vim anyway...
Laughs in vim you say... ua-cam.com/users/shortsZHoEYdocEBM 😆
why is if i didint call sum() in console in useEffect but have sum as dependency.
useEffect(() => {
console.log("sum is");
}, [sum]);
changing in state of setUserInput still call useEffect and console too. cause i didint call the sum() function there. i didnt understand that. my guess is that when change in state give new reference to sum(), thats why it behave in this way .
please help me
I don't fully understand your question, but in general, every render of a component will redefine a function that is created within the component - unless you apply useCallback.
Excuse me sir, so if we have a function that calls api that returns an array/object, should we put it in useCallback?
The answer to this is situational. If it is a function that fetches data and you want to call it every time the component is mounted, you could just define the function inside of useEffect and call it there. The useEffect dependency array should be empty so it is only called when the component is mounted. However, if you are defining this function outside of useEffect, then yes, you likely should put it inside of useCallback or the function will be re-created on every render of the component.
👍👍👍👍👍👍👍👍❤❤❤❤ thanks!
Welcome!
Great tnx
You're welcome!
I might be a noob in React but can anyone explain why we would ever use a function as dependency in userEffect? Would we wait for anyone to change that function definition then we will run our logic inside useEffect?
Thanks.
If you do not define the function inside of useEffect, you will receive a warning about missing dependencies. Also, the functions outside of useEffect are re-created every render. The way to avoid this re-creation is with useCallback. The way to avoid that is defining the function inside of useEffect when possible.
unrelated, but which colour scheme are you using here?
Github theme
why wouldn't you put either, [num1, num2] (only re-run when the numbers being summed change) or [sum()] (only re-run when the actual sum returned changed) as your dependency array? that way you aren't relying on a function ref for dependency.
also, useEffect isn't really a good place for this kind of code. it's better to place that into event handlers. useEffect should really only be for synchronization tasks.
useCallback is really only important when you are passing a function as a prop to another component. if you are doing this, then useCallback prevents re-renders of the tree caused by referential changes of the prop.
Hi Matthew - these are just examples to explain to a beginner what useCallback is and what it does. Kind of like examples in a textbook. You can refactor them and work with it in different ways. Don't consider tutorial examples to be "production ready" or the only way. So the answer to your "why" question - I'm just providing examples while explaining what it is, what it does, and how it is different than useEffect for beginners to understand.
can somebody please explain how he's able to see the error telling him to add the function to useCallback... is it an extension or something?
React will provide warnings and errors. No need for an extension to enable it.
Awesome
Thank you!
Fot mr this tutorial is best explaining useCallback, Thanks!
You're very welcome!