Common React Mistakes: useEffect - Part 1

2021 ж. 30 Нау.
45 467 Рет қаралды

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

Пікірлер
  • 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?

    @xq_nemesis@xq_nemesis3 жыл бұрын
    • 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.

      @jherr@jherr3 жыл бұрын
    • @@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.

      @xq_nemesis@xq_nemesis3 жыл бұрын
    • @@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.

      @jherr@jherr3 жыл бұрын
    • @@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 KZhead btw and I'm not just saying that!

      @mattmarkus4868@mattmarkus48682 жыл бұрын
    • @@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.

      @jherr@jherr2 жыл бұрын
  • 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

    @HadeFX@HadeFX3 жыл бұрын
  • 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!

    @ramoncardenas8433@ramoncardenas84332 жыл бұрын
  • I'm a React Js developer but i have l learnt so many new things. Thanks Jack. ✌

    @niamudeen000@niamudeen0008 ай бұрын
  • 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 !

    @gabrielmessiasdarosa3604@gabrielmessiasdarosa36042 жыл бұрын
  • 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.

    @BezzantSam@BezzantSam2 жыл бұрын
  • you provide one of the greatest programming content, Thank you so much

    @mehdiwadoud8098@mehdiwadoud80983 жыл бұрын
  • 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

    @PfalzerGbr@PfalzerGbr3 жыл бұрын
  • Your videos are truly amazing dude. Keep it up !!!

    @junzhongloo2170@junzhongloo21702 жыл бұрын
  • Was surprised by the colors and background of this episode but I like it.

    @BezzantSam@BezzantSam2 жыл бұрын
  • Wow! So good! Thank you.

    @jamesbest2221@jamesbest22213 жыл бұрын
  • This is a perfect sum up video, thank you!

    @shubhamh7451@shubhamh74512 жыл бұрын
  • Thanks you Jack, I would like to have a teacher like you!!! Your are a great young Master!!!

    @julian_pp@julian_pp2 жыл бұрын
  • what an awesome tutorial. Thanks

    @hamidrezakazemi7746@hamidrezakazemi77463 жыл бұрын
  • Real good content, as always. I wish it was with typescript though

    @zkayable@zkayable3 жыл бұрын
  • I really like how you explain, you are great, keep up with the good work! Thank you for doing this! :)

    @vnm_8945@vnm_89453 жыл бұрын
  • Very grateful to you. It is really helping me to master the react.

    @subhashgn1775@subhashgn17752 жыл бұрын
  • Thanks for the video. I loved it

    @sahilvig22@sahilvig222 жыл бұрын
  • This was a great video, thanks!

    @JulioDx3480@JulioDx34803 жыл бұрын
  • 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.

    @matthewlefevre5667@matthewlefevre56673 жыл бұрын
    • 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.

      @jherr@jherr3 жыл бұрын
  • 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

    @renanfilipe10@renanfilipe103 жыл бұрын
  • Thank you sir Jack

    @thanhnguyenhoai2727@thanhnguyenhoai27273 жыл бұрын
  • 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

    @amoljoshi23@amoljoshi233 жыл бұрын
    • Great suggestion!

      @jherr@jherr3 жыл бұрын
  • Much appreciated.

    @mmmmmmm8706@mmmmmmm87062 жыл бұрын
  • Besides everything, I love his eyes.

    @ibrahimkhurshid4339@ibrahimkhurshid4339 Жыл бұрын
  • Awesome!

    @guilhermegirardi@guilhermegirardi2 жыл бұрын
  • 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.

    @jasonadams5151@jasonadams51513 жыл бұрын
    • 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.

      @jherr@jherr3 жыл бұрын
    • @@jherr Hi Jack, have you created a video that addresses using objects as dependencies since this video?

      @dabears51979@dabears519792 жыл бұрын
  • Awesome ✌️✌️

    @attamjotsingh4474@attamjotsingh44742 жыл бұрын
  • 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 :)

    @sheneshperera@sheneshperera3 жыл бұрын
    • I'll think about that. I've never really liked the Egghead thing of those massive fonts.

      @jherr@jherr3 жыл бұрын
  • Great !!

    @aapiner@aapiner Жыл бұрын
  • Thanks :)

    @mateusznowak8542@mateusznowak8542 Жыл бұрын
  • 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?

    @jornejongsma@jornejongsma3 жыл бұрын
  • thx from Russia..!

    @d0paminer@d0paminer2 жыл бұрын
  • 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 !

    @NuMarK35@NuMarK352 жыл бұрын
    • 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.

      @jherr@jherr2 жыл бұрын
  • 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!

    @ignaciokornzaft7062@ignaciokornzaft70623 жыл бұрын
    • 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.

      @jherr@jherr3 жыл бұрын
    • @@jherr Thanks for your answer!

      @ignaciokornzaft7062@ignaciokornzaft70623 жыл бұрын
  • 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 :/

    @petarkolev6928@petarkolev69282 жыл бұрын
  • Common React Mistakes: useEffect → Jack Herrington useEffect 7:09 useCallback 12:48 useMemo 16:49

    @petronini@petronini3 жыл бұрын
    • Thanks Jorge! Forgot about that.

      @jherr@jherr3 жыл бұрын
  • 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.

    @marouaniAymen@marouaniAymen2 жыл бұрын
    • 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.

      @jherr@jherr2 жыл бұрын
  • 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-ch3 жыл бұрын
    • 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...

      @r-i-ch@r-i-ch3 жыл бұрын
    • You got me! ;)

      @jherr@jherr3 жыл бұрын
    • That's an excellent piece of advice!

      @jherr@jherr3 жыл бұрын
  • 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!

    @Ayomikun@Ayomikun3 жыл бұрын
    • Will do, thanks!

      @jherr@jherr3 жыл бұрын
    • @@jherr No worries, just hope it actually works!

      @Ayomikun@Ayomikun3 жыл бұрын
  • 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 KZheadrs and content creators shy away from this topic which is unfortunate because it's so important.

    @moarte6@moarte63 жыл бұрын
    • 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.

      @jherr@jherr3 жыл бұрын
  • I use a flag too within useEffect, didn't know I was doing good practises =o

    @2206901@22069013 жыл бұрын
    • 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.

      @jherr@jherr3 жыл бұрын
  • 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

    @ashimov1970@ashimov1970 Жыл бұрын
  • Can you share font and theme?

    @manansoni815@manansoni8153 жыл бұрын
    • Monalisa is the font, and I run a hacked version of Apollo Midnight. The hacking is to bring in the italics.

      @jherr@jherr3 жыл бұрын
  • Do you have a background in education? Because you are a seriously good teacher!

    @2penry2@2penry23 жыл бұрын
    • No, just another dev. :)

      @jherr@jherr3 жыл бұрын
  • Rules to live by: never pre optimize.

    @markclynch@markclynch2 жыл бұрын
  • what theam u r using

    @dineshreddy8915@dineshreddy8915 Жыл бұрын
    • Night Wolf [black]

      @jherr@jherr Жыл бұрын
  • 740 Likes with me..!

    @aniketbhalla1521@aniketbhalla15212 жыл бұрын
  • Maybe add a note saying that this is not valid for react 18 anymore

    @FranMcOd@FranMcOd Жыл бұрын
    • 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.

      @jherr@jherr Жыл бұрын
  • Jack could also be an auctioneer. So fast! Calm down please. Info is quite useful but it's not very easy to follow.

    @joostdeveloper2192@joostdeveloper21922 жыл бұрын
KZhead