Common React Mistakes: useEffect - Part 1

แชร์
ฝัง
  • เผยแพร่เมื่อ 30 มี.ค. 2021
  • Let's work through some common mistakes when using React's useEffect, useCallback and useMemo hooks (or not using them), and also their tricky dependency arrays. We will even come up with a helpful list of rules to live by.
    If you liked this video, buy me a coffee! www.buymeacoffee.com/bluecoll...
    Hope you folks enjoy this!
    👉 If you enjoy this video, please like it and share it.
    👉 Don't forget to subscribe to this channel for more updates: bit.ly/2E7drfJ
    👉 Weekly free newsletter: www.jackherrington.com/subscr...
    👉 Discord server signup: / discord
    💢 Watch our other videos:
    💟 Hacking your Github contribution graph: • Hacking Your Github Co...
    💟 Build a KK Slider Slider: • Build A K K Slider Sli...
    Thank you for watching this video, click the "SUBSCRIBE" button to stay connected with this channel.
    Subscription Link: bit.ly/2E7drfJ
    #reactjs #useEffect
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 78

  • @xq_nemesis
    @xq_nemesis 3 ปีที่แล้ว +7

    I’ve read some articles about using useCallback and useMemo on non expensive functions only decreases performance because you load more into memory then actually needed. I.e. not “optimizing” would have led to better performance. Do you agree with this?

    • @jherr
      @jherr  3 ปีที่แล้ว +16

      Yes, I mentioned in the video that useCallback and useMemo weren't necessary in this particular example. I used them here because I'm teaching them and I didn't want a massive unwieldy example. IMHO, the perf penalty on useCallback and useMemo isn't huge, but... I would only use then if I'm writing a custom hook, or I'm passing their results down to a tree of components where I don't know how they will be consumed, and that's because of referential integrity. Ken C. Dobbs has a great article on this and the conclusion is that it's primarily about referential integrity.

    • @xq_nemesis
      @xq_nemesis 3 ปีที่แล้ว

      @@jherr Thanks for the feedback! I find it very hard to know when or when not to use these kinds of optimizations as a beginner. Definitely going to look up that article.

    • @jherr
      @jherr  3 ปีที่แล้ว +11

      @@xq_nemesis For beginners I would start by always using them. That will give you some serious experience with hooks and make the transition into building your own custom hooks a lot easier. You can always pull them out for perf reasons. Start with the idea that everything from the top of the function to the return should be in a hook, and then come back from that if you get pushback.

    • @mattmarkus4868
      @mattmarkus4868 2 ปีที่แล้ว +1

      @@jherr Sorry to butt in here but when you say, "start with the idea that everything from the top of the function to the return should be in a hook", what are you referring to? I ask because I'm dying to take my mess of code and abstract the logic from the presentation. I just don't have the correct mental model for how to approach custom hooks at this point. Your channel is the best on TH-cam btw and I'm not just saying that!

    • @jherr
      @jherr  2 ปีที่แล้ว +4

      @@mattmarkus4868 Thank you! Feel free to jump on the Discord server and we can talk through any specific example you might have. As with all this stuff it's pretty subjective. If you are doing the "hooks as a store" thing then yeah, I'd pull that out into a custom hook. If the code is very specific to this one component, and would never be reused, then I might think about leaving it be, unless it's too big, and then possibly refactoring it into a custom hook in the same file.
      One of the reasons I think doing more custom hooks is important is because you start learning the rules of dependency arrays and referential integrity and getting a good feel for when to use useCallback and useMemo.

  • @anonymous_24-m1f
    @anonymous_24-m1f 9 หลายเดือนก่อน

    I'm a React Js developer but i have l learnt so many new things. Thanks Jack. ✌

  • @HadeFX
    @HadeFX 3 ปีที่แล้ว +1

    Hey Jack, recently discovered your channel. I have started a new front end project involving TS, React, Chakra UI and MobX. The content you're making at the moment is so relevant to me!!! Finding it really helpful. Keep up the good stuff, thanks

  • @ramoncardenas8433
    @ramoncardenas8433 2 ปีที่แล้ว +1

    I run into these problems every time I'm working on a react project. This one video is probably gonna save me a ton of time moving forward. Thank you!

  • @gabrielmessiasdarosa3604
    @gabrielmessiasdarosa3604 2 ปีที่แล้ว +1

    Hey, im from Brazil. Thanks for making these videos. I improve my code in React significantly every time i watch your tips. Thanks a lot ! Great work !

  • @PfalzerGbr
    @PfalzerGbr 3 ปีที่แล้ว +1

    Great video, it put these hooks in a little bit different perspective. It was nice starting from a broken app, and then break it again. Good to see the moving parts. Subscribe and bell button pressed :D

  • @junzhongloo2170
    @junzhongloo2170 3 ปีที่แล้ว +1

    Your videos are truly amazing dude. Keep it up !!!

  • @mehdiwadoud8098
    @mehdiwadoud8098 3 ปีที่แล้ว +3

    you provide one of the greatest programming content, Thank you so much

  • @vnm_8945
    @vnm_8945 3 ปีที่แล้ว +1

    I really like how you explain, you are great, keep up with the good work! Thank you for doing this! :)

  • @shubhamh7451
    @shubhamh7451 2 ปีที่แล้ว +1

    This is a perfect sum up video, thank you!

  • @julian_pp
    @julian_pp 2 ปีที่แล้ว +1

    Thanks you Jack, I would like to have a teacher like you!!! Your are a great young Master!!!

  • @subhashgn1775
    @subhashgn1775 2 ปีที่แล้ว

    Very grateful to you.
    It is really helping me to master the react.

  • @jamesbest2221
    @jamesbest2221 3 ปีที่แล้ว +4

    Wow! So good! Thank you.

  • @zkayable
    @zkayable 3 ปีที่แล้ว +3

    Real good content, as always. I wish it was with typescript though

  • @hamidrezakazemi7746
    @hamidrezakazemi7746 3 ปีที่แล้ว +2

    what an awesome tutorial. Thanks

  • @sahilvig22
    @sahilvig22 2 ปีที่แล้ว +1

    Thanks for the video. I loved it

  • @matthewlefevre5667
    @matthewlefevre5667 3 ปีที่แล้ว +2

    Thanks Jack! I don't ever use useCallback or useMemo. This video helped me to understand them better. As far as rules go: I tend to always pass a function when setting the value of useState just feels right for me.

    • @jherr
      @jherr  3 ปีที่แล้ว +1

      It's certainly the safest way to avoid any staleness. That being said, sometimes it can make the code a little klunkier and harder to follow.

  • @BezzantSam
    @BezzantSam 2 ปีที่แล้ว +1

    Was surprised by the colors and background of this episode but I like it.

  • @JulioDx3480
    @JulioDx3480 3 ปีที่แล้ว +1

    This was a great video, thanks!

  • @amoljoshi23
    @amoljoshi23 3 ปีที่แล้ว +7

    Awesome content Jack! So much learning condensed to 15-20 minutes. I would love to watch a video on some complex use cases of `useEffect`. For eg. 1. calling an API on on initial render -> saving that in state -> based on some interaction call the API again -> update state. 2. how many `useEffects` are too many? 3. Shortcomings of `useEffect` (where you need to end up using additional libraries like `react-use`). Thank you again for making fun videos

    • @jherr
      @jherr  3 ปีที่แล้ว

      Great suggestion!

  • @BezzantSam
    @BezzantSam 2 ปีที่แล้ว +1

    When I get discouraged about my skills learning React I can think back to learning guitar and bass. My fingertips hurt, I had to practice a lot for very little result. Eventually with a lot of hard work I was able to start playing some of the riffs and solos I so admired.

  • @guilhermegirardi
    @guilhermegirardi 2 ปีที่แล้ว +1

    Awesome!

  • @thanhnguyenhoai2727
    @thanhnguyenhoai2727 3 ปีที่แล้ว +1

    Thank you sir Jack

  • @mmmmmmm8706
    @mmmmmmm8706 2 ปีที่แล้ว +1

    Much appreciated.

  • @sheneshperera
    @sheneshperera 3 ปีที่แล้ว +11

    Hey Jack, awesome vid as always! Could you perhaps raise the zoom level of the code so it's a little easier to read on touch devices? Would be great if you could :)

    • @jherr
      @jherr  3 ปีที่แล้ว +4

      I'll think about that. I've never really liked the Egghead thing of those massive fonts.

  • @renanfilipe10
    @renanfilipe10 3 ปีที่แล้ว +3

    Thanks for the video! How about a video showing how to use the react profiler chrome extension? In this video, you can show how useCallback and React.Memo are used to avoid unnecessarily renders

  • @attamjotsingh4474
    @attamjotsingh4474 2 ปีที่แล้ว +1

    Awesome ✌️✌️

  • @ibrahimkhurshid4339
    @ibrahimkhurshid4339 ปีที่แล้ว

    Besides everything, I love his eyes.

  • @aapiner
    @aapiner ปีที่แล้ว

    Great !!

  • @jasonadams5151
    @jasonadams5151 3 ปีที่แล้ว +2

    Nicely done! I was admittedly hoping you were going to touch on the pitfall of using objects and functions as dependencies. Many people run into that not realizing that objects change even if they are equivocally the same.

    • @jherr
      @jherr  3 ปีที่แล้ว +3

      I'll get there, I had to lay the groundwork first. I had enough people coming to me with the basics stuff that I had to cover that first and I didn't want to overwhelm with a ton on content.

    • @dabears51979
      @dabears51979 2 ปีที่แล้ว

      @@jherr Hi Jack, have you created a video that addresses using objects as dependencies since this video?

  • @mateusznowak8542
    @mateusznowak8542 ปีที่แล้ว +1

    Thanks :)

  • @d0paminer
    @d0paminer 2 ปีที่แล้ว +1

    thx from Russia..!

  • @NuMarK35
    @NuMarK35 2 ปีที่แล้ว +1

    Hi Jack, great video thanks and greetings from Buenos Aires. Should I use useMemo and useCallback whenever I can? In which cases I wouldn't have to use them? Thanks a lot !

    • @jherr
      @jherr  2 ปีที่แล้ว +1

      IMHO, if you are building custom hooks you should use them. You should also use them if the function, or the data, that's being created, is passed to another component or being used in a dependency array. It's all about maintaining referential identity. When the data changes, the reference should change, when the data does not change, the reference should not change.
      Also, references only matter for arrays, objects, or functions. So if you are using useMemo to create a primitive type (string, number, boolean) then you should only use that if computing the value is time intensive.

  • @Ayomikun
    @Ayomikun 3 ปีที่แล้ว +1

    Great video, just a heads up, you might want to increase the bit rate of the video, or maybe decrease the resolution of your face cam when showing the parts in VS code. That should fix the weird blocky background effect showing on your VS code background!

    • @jherr
      @jherr  3 ปีที่แล้ว +1

      Will do, thanks!

    • @Ayomikun
      @Ayomikun 3 ปีที่แล้ว

      @@jherr No worries, just hope it actually works!

  • @ignaciokornzaft7062
    @ignaciokornzaft7062 3 ปีที่แล้ว +1

    Hi Jack! Thank you for another great video. Just one question: how can we get rid of the annoying "missing dependencies" error that shows on the console at 14:20? I get those all the time!

    • @jherr
      @jherr  3 ปีที่แล้ว

      Well, the fix there was to add `numbers` as a dependency or use the `setNumbers(oldNumbers => [...newNumbers])` state setter variant. I generally find that when this warning fires, it's for a good reason.

    • @ignaciokornzaft7062
      @ignaciokornzaft7062 3 ปีที่แล้ว

      @@jherr Thanks for your answer!

  • @jornejongsma
    @jornejongsma 3 ปีที่แล้ว +1

    Well, the rules that I try to live by... That's a good question, specially when it comes to refactoring components into smaller components. When and what to refactor?! Like with this component, you could start to create a button component for AddOne. But what do we give it, do we only give it the setter (setNumbers), so it can only function as a addOne button, or do we give it a onClick prop, so it can handle any kind of click event? But that wo don't refactor the evenhandler out of this component... And when is it time to introduce a state manager?

  • @r-i-ch
    @r-i-ch 3 ปีที่แล้ว +1

    I'll call you out on a common Mistake 😉: No .catch() clause error handling for the fetch!! I mean at least tack-on .catch(err => console.error(err)); 😇
    Good stuff as always...

    • @r-i-ch
      @r-i-ch 3 ปีที่แล้ว +1

      Addendum thought of only-my-preference 'not a big deal', I think it is more predictable to define a named function for doing the fetching within the useEffect, and then call that function by name. Also let's you comment it out when you're working on other things...

    • @jherr
      @jherr  3 ปีที่แล้ว

      You got me! ;)

    • @jherr
      @jherr  3 ปีที่แล้ว

      That's an excellent piece of advice!

  • @moarte6
    @moarte6 3 ปีที่แล้ว +5

    Hi Jack. Would you consider doing a tutorial on testing? Maybe talk about TDD and the best way to test hooks, maybe testing for Redux as well?
    Feels like most TH-camrs and content creators shy away from this topic which is unfortunate because it's so important.

    • @jherr
      @jherr  3 ปีที่แล้ว

      I agree and yep, I'll add it to the list. Sadly though, it's a long list. :( You can emphasize it by joining the Discord server and putting a request in #video-ideas.

  • @marouaniAymen
    @marouaniAymen 2 ปีที่แล้ว +1

    Thanks for the video, but I still use the hook useCallback when my function is used inside a dependency array of a useEffect hook, other than this, I don't see a big gain in using useCallback to always wrap my functions.

    • @jherr
      @jherr  2 ปีที่แล้ว

      In this case it’s not necessary that’s true. But in cases where you pass a function as a prop or return a function from a custom hook it’s good to useCallbavk.

  • @petarkolev6928
    @petarkolev6928 2 ปีที่แล้ว

    Rule #5 contradicts to the "useEffect" implementation here. I heard once Dan Abramov talking about how we shouldn't omit anything in our "useEffects"'s dependency array but I don't really see how this can be done every time :/

  • @2206901
    @2206901 3 ปีที่แล้ว +1

    I use a flag too within useEffect, didn't know I was doing good practises =o

    • @jherr
      @jherr  3 ปีที่แล้ว +1

      Yeah, if you need mounted state in another `useEffect` in the same area then you could do an `isMountedRef` with `useRef` where you have a `useEffect(() => { isMountedRef.current = true; return () => { isMountedRef.current = false; }}, []);` and use that to feed other `useEffects` so they don't have to track it as well.

  • @petronini
    @petronini 3 ปีที่แล้ว +5

    Common React Mistakes: useEffect → Jack Herrington
    useEffect 7:09
    useCallback 12:48
    useMemo 16:49

    • @jherr
      @jherr  3 ปีที่แล้ว +1

      Thanks Jorge! Forgot about that.

  • @2penry2
    @2penry2 3 ปีที่แล้ว +6

    Do you have a background in education? Because you are a seriously good teacher!

    • @jherr
      @jherr  3 ปีที่แล้ว +1

      No, just another dev. :)

  • @ashimov1970
    @ashimov1970 2 ปีที่แล้ว

    How come console.log("request finished") ever works? It should not since setNumbers(data) makes MyComponent re-render hence being trapped into an infinite loop that does not scope that console logging

  • @manansoni815
    @manansoni815 3 ปีที่แล้ว +1

    Can you share font and theme?

    • @jherr
      @jherr  3 ปีที่แล้ว

      Monalisa is the font, and I run a hacked version of Apollo Midnight. The hacking is to bring in the italics.

  • @markclynch
    @markclynch 2 ปีที่แล้ว +1

    Rules to live by: never pre optimize.

  • @aniketbhalla1521
    @aniketbhalla1521 2 ปีที่แล้ว +1

    740 Likes with me..!

  • @FranMcOd
    @FranMcOd 2 ปีที่แล้ว +1

    Maybe add a note saying that this is not valid for react 18 anymore

    • @jherr
      @jherr  2 ปีที่แล้ว

      Most of this video is about issues with the dependency arrays. And that doesn't change with React 18. The only thing that changes is the mount-unmount-remount behavior in development mode with strict mode enabled.

  • @dineshreddy8915
    @dineshreddy8915 ปีที่แล้ว

    what theam u r using

    • @jherr
      @jherr  ปีที่แล้ว +1

      Night Wolf [black]

  • @joostdeveloper2192
    @joostdeveloper2192 2 ปีที่แล้ว

    Jack could also be an auctioneer. So fast!
    Calm down please.
    Info is quite useful but it's not very easy to follow.