useCallback STOPS this React MISTAKE | useCallback React Hooks Tutorial

Поділитися
Вставка
  • Опубліковано 18 гру 2024

КОМЕНТАРІ • 129

  • @DaveGrayTeachesCode
    @DaveGrayTeachesCode  3 роки тому +14

    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

  • @ivanshoshkov
    @ivanshoshkov 2 роки тому +25

    This is what a real tutorial should be like. Not just blindly copy/pasting code but explaining the inner workings of stuff. Thanks man!

  • @chunli680
    @chunli680 3 роки тому +16

    Amazing content! There isn't much advanced React content on UA-cam. So glad you make this one :)

  • @andreysemenov3547
    @andreysemenov3547 Рік тому +1

    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.

  • @naganikhilbijjala1000
    @naganikhilbijjala1000 Місяць тому

    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

  • @haikoerinkveld4242
    @haikoerinkveld4242 2 роки тому +4

    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!

  • @slowcoding
    @slowcoding Рік тому

    Wow! The expiations open my eys to understand how the sum functions are created repeatedly. Awesome!

  • @viditgoel2909
    @viditgoel2909 Рік тому

    I really wish I had found an instructor like you earlier!

  • @ephratanebiyu5302
    @ephratanebiyu5302 2 роки тому +1

    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

  • @SayHi-y5j
    @SayHi-y5j Рік тому

    This is the clearest explanation video I have ever watched. Thanks

  • @brilliantatosam
    @brilliantatosam 2 роки тому +1

    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 😎

  • @allin.teamtube
    @allin.teamtube 2 роки тому

    for that van helen signature guitar, I should have known from the beginning that your content is gold.

  • @benarcher372
    @benarcher372 3 роки тому

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому

      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. 💯

  • @EdyLopez-o8n
    @EdyLopez-o8n 4 місяці тому

    Thank you Dave I really appriciate this content.

  • @r-iliass9587
    @r-iliass9587 2 роки тому

    My favorite web dev instructor

  • @rodanus7112
    @rodanus7112 Рік тому

    I'm so glad I found your channel. I really appreciate the great tutorials. Thank you!

  • @rajeshj4066
    @rajeshj4066 2 роки тому

    you are incredible. I am grateful that I found your channel

  • @ahmad-murery
    @ahmad-murery 3 роки тому +2

    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 💯🎉

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +1

      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! 💯🚀

    • @ahmad-murery
      @ahmad-murery 3 роки тому

      @@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

  • @mbmahesh9500
    @mbmahesh9500 2 роки тому

    Thanks Dave, this gave me detailed knowledge about useCallback hook.

  • @bishalkandel9976
    @bishalkandel9976 2 роки тому

    You are a very good teacher Dave. Appreciate your work. Kudos

  • @farasafeds9411
    @farasafeds9411 Рік тому +1

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Рік тому

      Thank you! I may not put one on Udemy, but I do plan to offer a course yet.

  • @blue_berry_pie64
    @blue_berry_pie64 Рік тому

    That's what I need, Thank you! the screen view is big for me easy to see Chrome dev tool. :D

  • @kishoreandra
    @kishoreandra 2 роки тому

    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 😖🙆 ...

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +1

      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.

    • @kishoreandra
      @kishoreandra 2 роки тому

      @@DaveGrayTeachesCode Ah Thanks alot Dave, how on earth I missed your videos 🤪 ....

  • @jiweihe3413
    @jiweihe3413 2 роки тому

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +3

      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.

    • @jiweihe3413
      @jiweihe3413 2 роки тому

      @@DaveGrayTeachesCode I see! Thanks! No wonder useEffect often defines a function directly inside it.

    • @jiweihe3413
      @jiweihe3413 2 роки тому

      @@DaveGrayTeachesCode I saw some people put [dispatch] in the dependency of useEffect. Is it necessary if they use dispatch inside useEffect?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +2

      @@jiweihe3413 dispatch won't change but the linter will give a warning if you don't include it in the dependency array.

  • @nahidfaraji5069
    @nahidfaraji5069 2 роки тому

    Crystal clear explanation. Thank you so much sir ❤️

  • @sinxenon3181
    @sinxenon3181 2 роки тому

    THANKS A LOT!!! Perfect explanation! 😍

  • @hosseinroosta5154
    @hosseinroosta5154 2 роки тому

    Fanstastic explanation. Thanks

  • @charanwebdevk6362
    @charanwebdevk6362 26 днів тому

    Thanks Dave.

  • @LearnTechWithRatan
    @LearnTechWithRatan 2 роки тому

    you earned yourself a subscriber, this is the perfect explanation

  • @upeksharanaweke3529
    @upeksharanaweke3529 Рік тому

    Great Tutorial.Thanks a lot 😇

  • @okskaren
    @okskaren 2 роки тому

    awesome video Dave,, thank you so much

  • @dev_ression
    @dev_ression 3 роки тому

    Very helpful tips, thank you!

  • @mohammadmahdialvansaz8001
    @mohammadmahdialvansaz8001 2 роки тому

    Great tut. Thanks

  • @aman7555
    @aman7555 3 роки тому

    Excellent content! 👏👏

  • @harag9
    @harag9 Рік тому

    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)

  • @aman7555
    @aman7555 3 роки тому

    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

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +4

      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. 💯

    • @aman7555
      @aman7555 3 роки тому

      @@DaveGrayTeachesCode thank you

  • @ranellabjata5170
    @ranellabjata5170 2 роки тому

    Great teaching skill. Thank you Sir. 👍

  • @QuadDrums
    @QuadDrums 2 роки тому

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому

      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.

    • @QuadDrums
      @QuadDrums 2 роки тому

      @@DaveGrayTeachesCode Thank you so much, much appreciated!

  • @shadabkhan681
    @shadabkhan681 2 роки тому

    Thanks for this Gold lesson.❤

  • @Ranjithkumar-ll5rb
    @Ranjithkumar-ll5rb 2 роки тому

    nicely explain thank you 😀

  • @tamlselvan9072
    @tamlselvan9072 2 роки тому

    Thanks Dave 😀

  • @vladserhiychuk8925
    @vladserhiychuk8925 2 роки тому

    Great. Thanks.

  • @aleksprimetv
    @aleksprimetv 2 роки тому

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +2

      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! 🚀

  • @harrycohen2722
    @harrycohen2722 2 роки тому

    what vs theme are you using? looks amazing

  • @sonamohialdin3376
    @sonamohialdin3376 2 роки тому

    So good tutorial

  • @dzentsetsu5607
    @dzentsetsu5607 3 роки тому

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +3

      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

    • @dzentsetsu5607
      @dzentsetsu5607 3 роки тому +1

      @@DaveGrayTeachesCode 🙏

  • @caffeinated-pixels
    @caffeinated-pixels 3 роки тому

    Good video Dave. I learned the hard way why you shouldn't ignore those ESLint warnings in React. It wasn't fun 🤣

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +1

      So true about ESLint warnings! Thanks for the kind words! 💯

  • @ankitaburman5406
    @ankitaburman5406 Рік тому

    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 ?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Рік тому +1

      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.

  • @TradingBloke
    @TradingBloke 10 місяців тому

    you are the best

  • @mhamdking4860
    @mhamdking4860 28 днів тому

    شكرا

  • @thilakraj6225
    @thilakraj6225 2 роки тому

    Why did we had infinite rendering. Can you please explain that part and how did you avoid that?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому

      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.

    • @thilakraj6225
      @thilakraj6225 2 роки тому

      Thanks Dave!

  • @zourdy697
    @zourdy697 3 роки тому

    damn your fun dude dave

  • @Tim00011-t
    @Tim00011-t 8 місяців тому

    This is really amazing! But laughing in vim anyway...

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  8 місяців тому

      Laughs in vim you say... ua-cam.com/users/shortsZHoEYdocEBM 😆

  • @lobsanggyatso6280
    @lobsanggyatso6280 2 роки тому

    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

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому

      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.

  • @farisnaufal8579
    @farisnaufal8579 2 роки тому

    Excuse me sir, so if we have a function that calls api that returns an array/object, should we put it in useCallback?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому

      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.

  • @mariusguissou4282
    @mariusguissou4282 2 роки тому

    👍👍👍👍👍👍👍👍❤❤❤❤ thanks!

  • @mehrabkor8591
    @mehrabkor8591 2 роки тому

    Great tnx

  • @phugia963
    @phugia963 2 роки тому

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +1

      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.

  • @bertrodgers2420
    @bertrodgers2420 2 роки тому

    unrelated, but which colour scheme are you using here?

  • @m4ttheweric
    @m4ttheweric 2 роки тому

    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.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому

      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.

  • @novanoskillz4151
    @novanoskillz4151 2 роки тому

    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?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому

      React will provide warnings and errors. No need for an extension to enable it.

  • @miteshsagar8149
    @miteshsagar8149 3 роки тому

    Awesome

  • @kakhabervk9405
    @kakhabervk9405 2 роки тому

    Fot mr this tutorial is best explaining useCallback, Thanks!