Common React Mistakes: useEffect - Part 2

  Переглядів 25,425

Jack Herrington

Jack Herrington

3 роки тому

Let's build on part 1 ( • Common React Mistakes:... ) by looking at the cleanup function on useEffect to make sure that we are using timeouts, intervals and registering event listeners properly.
Part 1: • Common React Mistakes:...
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

КОМЕНТАРІ: 66
@vigneshs2886
@vigneshs2886 3 роки тому
You are truely a Principal software engineer.
@corleroux
@corleroux 2 роки тому
Apart from the tutorials, which are absolutely fantastic, I love the fact that you engage with your followers and actually respond to the questions asked in the comments. I've picked up 2 things that's been bothering me just by reading the threads below. Thanks for a great channel and keep up the good work and focus.
@petergrant6498
@petergrant6498 3 роки тому
gold gold gold gold gold!! These are some of the best quality overviews for more advanced concepts in React. Completely applicable to real-world scenarios, and delivered in such a wonderfully approachable way! Amazing channel.
@csl4jc
@csl4jc Рік тому
Great video: great production values, good use of time, nice presentation, pleasant personality, and super-useful info. I love your work!
@PfalzerGbr
@PfalzerGbr 3 роки тому
I just had a tech challenge for a React job interview last week. Bit more complex exercise, but this was the bottom line. The component didn`t unmount, so no trace of the leak in the browser. I was writing the required component tests first, so Jest caught me the memory leak, I went with the clearInterval solution. I think It went well, will see :) It`s nice to see your solution retrospectively, gives me some confidence.
@arslanali774
@arslanali774 Рік тому
i was working on vuejs previously, just recently started learning react with real intent and found your channel, everything started to fall in place and made sense to me, ive seen other videos on react as well. this is great content. highly appreciate the effort. thanks jack.
@subhashgn1775
@subhashgn1775 2 роки тому
Very grateful to you. It is really helping me to master the react.
@MovieMAZASUCCESS
@MovieMAZASUCCESS Рік тому
well I think it goes over my head but I'll try to practice and come back to understand properly.
@presida3927
@presida3927 2 роки тому
Thank you so much uncle, Jack.
@jr-hp7er
@jr-hp7er 2 роки тому
wow...just wow....Need more advanced hooks videos or require an entire series just on hooks....Awesome Jack, loved it keep it up :)
@lescobrandon2202
@lescobrandon2202 3 роки тому
Awesome lesson again!
@vakhtangnodadze4802
@vakhtangnodadze4802 Рік тому
I end up saying the same thing on your videos, but that's pretty much the only thing I can say. Great video, great explanation and examples. Thank you!
@HIghtowerSever
@HIghtowerSever 3 роки тому
Liked. Subscribed. Thanks.
@user-oy4kf5wr8l
@user-oy4kf5wr8l 2 роки тому
Great video! Buddy!
@julianschmidt6281
@julianschmidt6281 2 роки тому
Nice content. Thank you
@m0hammedimran
@m0hammedimran 2 роки тому
This is priceless. 👀👍🏽
@soobhhann6746
@soobhhann6746 2 роки тому
thank you are the best
@Berbersky15
@Berbersky15 2 роки тому
I LIKE THIS GUY!
@RO-nb6mz
@RO-nb6mz 3 роки тому
Really glad to have discovered this channel last year. Tutorials that aren't common on the internet. Speaking of uncommon tutorials...Would you do one on plugin architecture & implementation? I mean like how shopify or Wordpress is a platform & provides facilities for plugin development for added functionality not included out of the box? Wonder how no one hasn't done it by now. Your easy to understand explanations are tip top!...continue with good work
@jherr
@jherr 3 роки тому
I've done a video on using ScandiPWA for plugins, and also another on using Module Federation for plugins. I think the ScandiPWA has more legs because it's specifically designed to be a plugin framework, and they've recently done a lot of work that I haven't had time to cover to allow for plugins on CRA and NextJS. Here is a link to their site: plug-js-landing.vercel.app/
@Shahbaz__ali_
@Shahbaz__ali_ Рік тому
I love the deep knowledge of react that you provide like how everything stuff work under the hood.. but one thing I am just wondering like react give me a warning of memory leak when we fetch data.. please make a video for it when fetching a network request and so on..
@b4bass
@b4bass 2 роки тому
Hi Jack - Great tutorial ( you really know your stuff for sure) - I'm trying to extract your code into an actual component but it's killing me. Is there anywhere I could download a working copy of the code used in this video? I'm sure I can then get it working as a functional component. Much appreciated.
@mmmmmmm8706
@mmmmmmm8706 3 роки тому
Great video! Would be great to dig into why using the previous timer state object solved the counting problem. I suppose the closure it creates is the magic there.
@jherr
@jherr 3 роки тому
Can you give me a time reference?
@mmmmmmm8706
@mmmmmmm8706 3 роки тому
@@jherr , thanks Jack ... at 6:07 ... “ what u need to do is use the version of setState” that returns the prev version of state setter that gives u the current value object as a function. This is the closure i was referring to.
@mmmmmmm8706
@mmmmmmm8706 3 роки тому
6:07 to 6:21 where currentCount is mentioned. Im at point where i can get thrown off by this in my code, so its super helpful here to step back and walkthrough samples like this ... like u said to build up some confidence and lock in understanding. Oh, i wish you had a paid course! Id be there 👍
@jherr
@jherr 3 роки тому
​@@mmmmmmm8706 Ok gotcha. The trick is in realizing that there are two values here, the "count" which is state managed by React, and then that "captured count" which is zero because that was the value of "count" at the time when the useEffect callback was run. "Captured count" will never change. So in order to get access to the real count we use the callback version of the state setter which is guaranteed to give us the current state value, and then we can add one to that and everything works. Ah... closures.. they are amazingly powerful, but also super hard to reason about at the same time.
@mmmmmmm8706
@mmmmmmm8706 3 роки тому
@@jherr , couple in the fact that useEffect is run after render ... still easy to confuse myself here, my components can sometimes display an old value when im expecting the new one to render(sorry if thats confusing). Much appreciated, Jack!
@Siddharathbhardwaj
@Siddharathbhardwaj 3 роки тому
Very nice video about cleaning up, in between I want to know the difference between functional and class based component? Why it needed for Facebook to introduce that...
@jherr
@jherr 3 роки тому
Class based components came first. Then function based components. But originally functional components couldn't have state. So FB added hooks. And now most folks choose functional components as the primary mechanism for defining components because they are simpler and more performant than class based components.
@Siddharathbhardwaj
@Siddharathbhardwaj 3 роки тому
@@jherr thanks
@fastsolution
@fastsolution Рік тому
what do you mean at 18:24 that if the ref changes (move that to a different div ... ?) i didn;t understand
@ejikeezekwunem4162
@ejikeezekwunem4162 Рік тому
Without the "clearInterval", my counter increases in multiplication of two, like : 2, 4, 8,... I don't know why that is.
@jherr
@jherr Рік тому
Probably hot module reloading. Try refreshing the page.
@ejikeezekwunem4162
@ejikeezekwunem4162 Рік тому
@@jherr It was as a result of useEffect being called more than once in React 18 StrictMode. You treated that in another tutorial. Thank you so much for your great contents.
@ManInSombrero
@ManInSombrero Рік тому
*_React: Turning building of basic UIs into rocket science since 2013™_*
@jherr
@jherr Рік тому
giphy.com/clips/XBLRIlD2Hw2kONXwzI You're not wrong.
@mani8586
@mani8586 2 роки тому
Can clearInterval(intervalID) only be used in useEffect cleanup variant as the same thing I tried in onclick event but it didn't worked ?
@jherr
@jherr 2 роки тому
I'm not sure I follow. Are are you creating a timer on a click? If so I would store the returned interval value in a `useState` value and then use a cleanup function in a `useEffect` (that did nothing else) to kill the interval on component unmount. That's a pretty complex way to go. What would be easier would be to have some state that said whether or not you should have a timer. And then a useEffect that watched that toggle state and creates/destroys the timer as I showed in this video. To talk more about this jump on my Discord server in the #react channel.
@TheMariukz
@TheMariukz 3 роки тому
What camera did you use to film outside?
@jherr
@jherr 3 роки тому
Sony A7 with a 35mm lens with ND filter.
@tirumaleshae7515
@tirumaleshae7515 Рік тому
Can anyone explain at 5:55 why count value in setInterval function is 0 even after components rerender and creates new closure?
@jherr
@jherr Рік тому
Because the effect function is still the same since the effect function wasn't re-created when the component was re-rendered since the dependency array is empty.
@michaelm8044
@michaelm8044 Рік тому
Could you please tell me the theme?
@ShaggyKris
@ShaggyKris 3 роки тому
I've been working in React hooks since they went live, and I still am having trouble knowing when to use useCallback. What are general use cases and advanced use cases to utilize the hook?
@jherr
@jherr 3 роки тому
Any time you are creating a function within a component or in a custom hook. For components you might be able to get away with NOT using it if you are NOT passing it to another component. The issue is really referential integrity. useCallback ensures that you don't create a new callback function unless the underlying data used in the callback changes.
@ShaggyKris
@ShaggyKris 3 роки тому
@@jherr So say you are building a form and not using a form library, would you use useCallback for setter functions, or can you use simple arrow functions? Would useCallback only be useful if these setter functions would be passed to controlled components with deeper propagation?
@jherr
@jherr 3 роки тому
@@ShaggyKris Yeah, in the case where you are not using a form library then the usual arrow function is probably fine. I totally understand that this advice is basically the opposite of Kent C Dobbs is saying in his article about it. His position is, use anonymous functions unless you know you need referential integrity. And mine is basically use useCallback unless you know you don't need referential integrity. But I think those are actually the same position, it's just that I think, if you are just using hooks and custom hooks for state management, you need referential integrity a lot more than you think you do because dependency arrays depend on it. Now if you are just using a few hooks here and there, and you are using a state manager for the big state management, then I don't think this stuff really matters all that much.
@ShaggyKris
@ShaggyKris 3 роки тому
@@jherr Is there a way to use useCallback for things such as event listeners to maintain current state values when executing functions without the need of using a useEffect that depends on said value, removes the previous event listener (via return), and then adds a new event listener with the current function reference? Or would you need to update a ref or something to achieve that?
@jherr
@jherr 3 роки тому
@Kristofer Pervin Totally a good thing to do: const onAdd = useCallback(() => setCount(count + 1), [count]); To me is more declarative than: const onAdd = useCallback(() => setCount(c => c + 1), []); And it's certainly better in the case when you have several pieces of state all that need to be adjusted.
@mikewilliams5571
@mikewilliams5571 2 роки тому
Why did you use a useCallback inline function instead of an arrow function?
@jherr
@jherr 2 роки тому
It's not particularly necessary in this case. If I were to create a callback as part of a custom hook, or I passed it to another component, then I would always recommend using useCallback in that case because of referential integrity.
@mikewilliams5571
@mikewilliams5571 2 роки тому
@@jherr Do you have any further resources on referential integrity and performance optimisation, please?
@jherr
@jherr 2 роки тому
@@mikewilliams5571 I have covered it in the past, but I don't have a specific video on it. But Kent C. Dobbs has a good article on it: kentcdodds.com/blog/usememo-and-usecallback#so-when-should-i-usememo-and-usecallback I will say that I vary a little from Kent, in that I have a preference to use useCallback and useMemo and his preference is to not to use them until there is a problem.
@delcambrem
@delcambrem 2 роки тому
Where does “currentState” come from?
@jherr
@jherr 2 роки тому
Can you give me a time reference into the video so that I can be a bit more helpful?
@delcambrem
@delcambrem 2 роки тому
@@jherr Of course. 6:22, line 12. I'm assuming "currentState" is something that can be called on any state, but I"m new to React and just haven't seen or heard of this, and not sure what the difference would be between "count" and "currentCount."
@jherr
@jherr 2 роки тому
@@delcambrem Ah, I see. There are two ways to call the state setting function returned from useState. The first is with the new value you want for the state. And the second is with a function, and that function gets the current value (so "current count" in this case) and then it should return a new count based on that original value.
@amirologi
@amirologi 2 місяці тому
The ref part is a bit confusing!
@DedicatedManagers
@DedicatedManagers 3 роки тому
Maybe I’m too tired to think straight… How come we don’t use useCallback on click handlers like onClick?
@jherr
@jherr 3 роки тому
By the book we should have been all this time, but... in a lot of cases it doesn't matter. But if you are building a custom hook, or passing the click handler down to sub-components then you should use it because of referential integrity. The downside is a very small performance penalty in the cost of the useCallback call and the comparison of the dependency array.
@simoncordova5655
@simoncordova5655 3 роки тому
Was this live? If so, shucks I just missed it by 12 mins! :/
@jherr
@jherr 3 роки тому
Nope. Live happens on Friday. This is new. ;)
@eleah2665
@eleah2665 3 роки тому
So what's the deal with the guitars in the background of youtube tech videos? Is that a meme, insider joke, or coincidence? Never a banjo, piano, or kazoo?
@jherr
@jherr 3 роки тому
Why not? It looks cool. That's just a wall in my office. :) No inside joke.
Common React Mistakes: useEffect - Part 1
19:57
Jack Herrington
Переглядів 45 тис.
Making React Context FAST!
33:34
Jack Herrington
Переглядів 84 тис.
How to get a FREE HYPERCHARGE SKIN!
02:07
Brawl Stars
Переглядів 16 млн
3 React Mistakes, 1 App Killer
14:00
Jack Herrington
Переглядів 111 тис.
Typescript for React Components From Beginners to Masters
27:51
Jack Herrington
Переглядів 160 тис.
Mastering React Memo
26:56
Jack Herrington
Переглядів 130 тис.
No const! How NOT To Give A JavaScript Talk
10:28
Jack Herrington
Переглядів 13 тис.
Picking From 20 React State Managers
35:18
Jack Herrington
Переглядів 82 тис.
Mastering React's useEffect
25:20
Jack Herrington
Переглядів 169 тис.
React Hook Form & React 19 Form Actions, The Right Way
16:08
Jack Herrington
Переглядів 35 тис.
You're Doing React Hooks Wrong, Probably
20:11
Jack Herrington
Переглядів 63 тис.
Finally Fix Your Issues With JS/React Memory Management 😤
20:13
Jack Herrington
Переглядів 74 тис.
HUAWEI БЕЗ GOOGLE: ЕСТЬ ЛИ ЖИЗНЬ? | РАЗБОР
11:49
УШЕЛ С iPHONE 15 PRO MAX НА PIXEL 8 PRO: ЭТО ЖЕСТЬ
32:33
Арсений Петров
Переглядів 55 тис.
How Neuralink Works 🧠
0:28
Zack D. Films
Переглядів 23 млн