In Defense Of useEffect - React's Most Dangerous Hook
Ғылым және технология
useEffect was essential to the success of React hooks. It deserves some crap, but nowhere near as much as we give it. #react #javascript #webdevelopment
ALL MY CONTENT IS FILMED LIVE ON TWITCH AT / theo
ALL MY BEST MEMES ARE ON TWITTER FIRST / t3dotgg
ALL THE COOLEST PEOPLE ARE IN MY DISCORD t3.gg/discord
ALL MY VIDEOS ARE POSTED EARLY ON PATREON / t3dotgg
Everything else (instagram, tiktok, blog): t3.gg/links
Пікірлер: 130
The cleanup function being the return value of the effect function has a crucial advantage that makes the trade off much more favorable. It can just pick up where the effect function ended, reusing its scope. You simply can't do that with a cleanup function that is in a separate argument.
@karixening
Жыл бұрын
EXACTLY, like if you want to add and remove an event listener. Otherwise you'd have to memoize the function reference.
@lukeyd13
Жыл бұрын
You could return the arguments you want to be passed to your clean up function if you wanted to hand an api like Theo is proposing and having access to the scope
@inwerpsel
Жыл бұрын
@@lukeyd13 If the criticism of useEffect is that its cleanup syntax is not clear enough, I don't see how that would improve it, on the contrary. It would still be returning something related to the cleanup, only now you can't see immediately what's going to happen with those things. It also hides the fact that these values are really only needed in the cleanup. It would also make React's job harder. Currently all React has to do is run that function. If there would be a cleanup function signature, with complex stuff being reflected back, React would need to keep track of these objects and pass them as arguments.
Can I just say that if I read and watch another useEffect guide using a simple counter I will go mad. It has no real world use case and is way overly simplistic which leads to useEffect being misused
@hunterwilhelm
Жыл бұрын
It has a very ambiguous name and description. Syncing data with streams and subscriptions are two of the good use cases for use effect. The console.log is a stream in a sense too
@TypingHazard
Жыл бұрын
Yeah counters and to-do lists and Hello Worlds aren't usually very good examples of good code. They tend to drift into WAT territory from the old "let's talk about JavaScript" video, where it's like... it's cool that the framework allows you to do this, but if you ever actually do it you're gonna have a hard time getting your MR approved
@kimbapslayer1995
Жыл бұрын
Easy videos for creators. Basically lazy easy money
@RudraSingh-pb5ls
Жыл бұрын
@@hunterwilhelm hope theo isn't teaching useEffects the traditional way
I think the main problem with the API proposed at 9:30 is that clean-up functions often need access to the scope of the main useEffect callback. For example, to disconnect a websocket connection instantiated via a local variable within the useEffect.
@hunterwilhelm
Жыл бұрын
Perhaps an alternative could be usEffect(()=>{ // do stuff return { cleanup: () => {}, deps: [args] } }); Since use effect always runs at least once I don’t see why we couldn’t return them from the function with the cleanup and have them named that way
@samuelgunter
Жыл бұрын
@@hunterwilhelm deps shouldn't go there incase the synchronous effect takes long
@brettstoddard7947
Жыл бұрын
could that be passed around with a setstate?
in addition, there is also an implicit behavior of passing an empty deps array [] has a special meaning of run once
useEffect is just how you declare code that should be run as a side effect of rendering. This is why the default behaviour of useEffect (with no dependency array) is to run on every render. The dependency array should be constructed from the code that is run inside the useEffect - its a way of telling react that the outcome of the function will only change if these state variables actually changed, as an optimization. This is why it "runs when a value changes", because state updates cause components to render.
I really like your video. Rather than just giving a short tutorial, having a talk on the concept makes me reflect on my code and the way I think. Keep going👍
It’s amazing that we get these free videos where a senior developer discusses this information. Big fan of Theo
Excellent video, I am watching the video still, but I figured I post my questions while I watch. I am fairly new to React, and I am still trying to understand the useEffect. What is mount and unmount and what is implicit? OK, thank you Theo for the video it was very insightful and did help me to understand a bit more the useEffect. Also, I am reading the documentation you were looking at in this video. Would it be possible though if you can explain how to create your own hooks? I had no idea you could do this? I went on a website and it mentioned something about creating your own hooks, how is this possible!?!?! Thank you once again Theo, love your content your knowledge on React is amazing!
Regarding not updating state with useEffect, how do you feel about using it as part of a debounce pattern to do some server-side validation (eg email in use or something) then updating state? (Which by the way you also want to run on mount, so just triggering onchange would not be sufficient)
After my initial baptism into HTML+CSS+JS, one of my first jobs used Typescript and Knockout MVVM for the frontend. It was a .NET 4.5 C# ASPNET app with razor templates that handed off to our typescript view models using knockout for reactive forms and front ends. I would like to think there would always be a contingent of reactive and 'hook like' APIs even if React didn't do it, but the way it went down definitely surged the adoption of this kind of state reactivity flow abstraction, and I think has had network effects on libs like solidjs.
@kimbapslayer1995
Жыл бұрын
Wtf are you saying
Probably my only gripe with cleanup callback as a return of useEffect is that it means you can't use async callback functions easily. You either have to declare a new async function inside and call it, self call anonymous function (which is ugly as heck) or use `then` which is not really possible if you need multiple awaits (like in a loop or something).
I've been experimenting a lot with observables in react and I dare to say it might kill hooks the way we use it. I see a couple of advantages for the useObservable approach where whenever you have memoized state in it's own and doesn't trigger re-renders whenever updating values. So this has got me not using useEffect as often anymore and other hooks. Because if you think about it some hooks kinda exist because of useEffect
@jussinevavuori2598
Жыл бұрын
Can you show an example? A github link or something?
Theo, as I learn useEffect (I have a decent understanding of useState) what is the next hook you would recommend a newbie such as myself to learn next?
@Valyssi
Жыл бұрын
You might've already looked into it by now, but useReducer is pretty important. I see a lot of people jump straight to redux or a complicated network of useState's and handlers where useReducer would be much more suitable. Refs and context are also valuable, but as with useEffect it's just as important to know when NOT to use them. After that, memoization (useMemo and useCallback) are important in some situations, but most of the time you should be fine with just the previous hooks.
I never have the feeling of wasting my time on this channel, learning new things every time 👍 Thanks Theo
"I've seen people setting a second useState for that double count, and then, in an effect, when count changes: set double count to the new value" Theo's been reading my code 😂
If I'm not supposed to use useEffect for data fetching, what's the alternative?
My main issue with useEffect is that it feels like it doesn't really adhere to the single responsibility principle.
@Davidlavieri
Жыл бұрын
that's why you use múltiple ?
06:14 the unintuitive behaviours of react was something that really annoyed me when I started learning it. There's always a hook or sequence of declarations that does not run the way you'd expect based on pure JS knowledge
IMHO I think they want us to think useEffect is linked to lifecycle of the data and not the component. Thus any creation/change/destruction would trigger the useEffect. I think it's just that it made more sense having a separate handler inside effect for the destruction part. And i think no deps array basically means any data creation/change/destruction should trigger the useEffect. This was my understanding and in fact it was because of hooks, especially useEffect, that convinced me finally adopt react as my go to UI framework.
But I love using useEffect for update chains :) until I have to work on the project next week.
I'm still just learning React, but I'm so glad that I don't have to worry that much about mounting and such. Weird timing on this video, I spent 40 minutes earlier watching Jack Herrington videos on the topic to make sure I fully understood it because I saw how easy it was break.
So how would one fetch data on component mount without useEffect and without any third party libraries?
@MrHamsterbacke756
Жыл бұрын
You can't
@mil0s251
Жыл бұрын
@@MrHamsterbacke756 then is that a bollocs he says in the vid?
@ebrelus7687
Жыл бұрын
And how such library does it? Is it the only hook of power?
I just love your videos
idk how I never realized code outside of components runs. like, obviously it runs. and i've done it for like simple constant declaration before. but when you pointed out that "javascript runs" it kinda blew my mind. feel kinda dumb lol
I remember writing HOC before hooks🥶
Do you think hooks are actually just facade on top of components?
Wait, dont't useEffect for data fetching ? Where am I supposed to making my data fetching ? '-'
In summary. Never deny the advantages a good hook can bring you at the right time.
Great energy !
"You could argue useQuery should be built into React at this point" Damn the foreshadowing here! 🤯
Good points as always
Also, doesn't React now do a simulated mount (or something like that) where useEffect actually triggers twice on the first page render? E.g., simulated mount, unmount, then real mount?
@DubiousNachos
Жыл бұрын
Only if you're in both dev mode and in strict mode. If you don't have both, it'll just fire once. It's mainly meant to help test the resilience of a useEffect hook
i want to fetch data and not use external library such as react-query and such. how do i do that with pure react?
@jackwakeham1808
Жыл бұрын
Use fetch inside a useEffect or callback. Await the data and add it to state using useState. Then render the data however you like.
@mumu2692
Жыл бұрын
checkout web dev junkie, theres a video talk about ur question
@michalzarddev
Жыл бұрын
useEffect(()=>fetch("api").then("extract data here"),["leave this empty is just wanna run it once on route/component loaded"])
@guygolan3685
Жыл бұрын
Yeah ill ephasize. In this vid he says dont use useeffect because using react query is better. If i opt to not use external libs, the only option is useeffect or there is a third way?
@oscarljimenez5717
Жыл бұрын
@@guygolan3685 depends, maybe u wanna fetch on user actions, so u don't need useEffect. But if u wanna make some fetch on initial render, u have to do it in a empty array useEffect and include a controller signal for the unmount part. If u want both, just mix them, but is a mistake create a useEffect for handling both actions.
Doesn't the clean up function also run on every rerender?
@MrHamsterbacke756
Жыл бұрын
No
@Davidlavieri
Жыл бұрын
Only if the dependencies changes
Astonishing abstract thinking skills. I wish I had a brain that big lol
I don't get why returning a callback is weird for having some "unmount logic" to be executed. Isn't it easier to create references to variables within the the useEffect function using closures?
ok but if you want something to run on every render, why don't you put the code in the component function, before return and if its a lot of code just wrap it in a normal function? Why use useEffect without the second argument? Unless it results in a different behaviour, useEffect should just throw if it doesn't get an array(in JS. Typescript would catch that earlier). Obviously now it's not a great idea because of backwards compatibility but ideally it should throw imo.
@jeffreydelossantos8667
4 сағат бұрын
for cleanup, useEffect should be used merely for side effects. and it runs after rendering
Why are you not talking about just.js?
Am I a crazy, or nobody knows about template element in HTML?
This has just convinced me that React's model of running code that does non-render things in a render function is fundamentally broken, and that Vue/Svelte/Solid are doing it right with having all code in the component run when the component is first created, with anything else having to be explicit. I don't want the full power of a turing complete language for reactive renders, when a templating DSL can do that much better. I do want turing completeness for the non-rendering/business logic instead, and that part should have as few footguns as possible
Not me using useEffect for fetching data😎
The problem with useEffect is its too easy to use it for everything. And that's problematic when you don't recognize there is a better way to achieve most of what you're doing with useEffect.
@hunterwilhelm
Жыл бұрын
It’s a complicated function it should have a complicated name
@ebrelus7687
Жыл бұрын
Can you add examples? Or is it like reduce vs other ho functions?
Just overheard a conversation in my team: "Any opportunity you can take to remove useEffect do it, it just makes everything better"
"you can run js outside your components" This is a really, really, really bad idea... I frequently run into memory leaks on the server side because a third-party library decided to introduce side-effects outside a component's scope.
@ebrelus7687
Жыл бұрын
Which libraries have such "feature"?
The fundamental problem with React is components re-run in their entirety every re render.. We're all learning at the same time that this is wrong. Components should behave like Solid or Svelte
@uziboozy4540
Жыл бұрын
The problem with React is that it's so widely adopted. People should really stop using that garbage.
@Toulkun
Жыл бұрын
@@uziboozy4540 Problem with React is that is sucks ass as long as hooks exist in it, they need to learn from Angular, Angular will always be more intutitive and easier to read.
@uziboozy4540
Жыл бұрын
@@Toulkun have you seen the new proposal for Angular? Fucking signals aka hooks - because people don't have the brain capacity to learn RxJs 🤦♂️
Are render props considered bad practice? Isn't this the whole architecture of headless UI?
@MrHamsterbacke756
Жыл бұрын
You don't need the render props pattern for the most cases anymore
@ebrelus7687
Жыл бұрын
@@MrHamsterbacke756 When that's still needed?
Proposed new title: "Hooks good, useEffect is a dangerous and awful abomination that should be replaced with a saner hook ASAP"
Why not have unique hooks for mount/unmpunt? And keep the useEffect only for updates? Since JS is functional you can just define 1 function and pass it to both hooks...
@OryginTech
Жыл бұрын
Ain’t nobody got time for that. The way it is, is perfect lol
@fischi9129
Жыл бұрын
@@OryginTech I mean, if we continue like this react gona die in a couple of years and get substituted by stuff like solid which does the exact same thing, the exact same way, but better anywhays :)
@OryginTech
Жыл бұрын
@@fischi9129 react “has been dying in a few years” since the time it was officially announced 😂😂😂 let’s wait for that day sometime in the next 40 years 💀
@fischi9129
Жыл бұрын
@@OryginTech I mean, let's be real here, tell me one thing react does better tan solid for example (except having more libraries, which is not a big deal since more and more libs become framework independant or already are). There isn't even a reason not to switch to it if libs are there as well since there is no learning courve at all. Any new project has no reason to choose react over solid. Because Solid is an objectively speaking better react. so tell me 1 thing react does better than solid and/or is catching up to solid which does everything react does but better with 0 learning courve to it. No need for 40 years, once libs catch up to react on solid for instance, if react doesn't innovate it's trashware... it still kinda is, because the only feature I see that changed something to react 18 was that the dev mode became useless since reacts most important hook now officially behaves differently from dev to prod.... See it in a different light, if I offer you the same car, but it uses less fuel, goes faster and now has leather seats instead of cheap trashy seats that break your back with no extra cost... why would you refuse it? I mean, your brain can be working pretty badly, but if there are only benefits there is no point on not switching to it.
@OryginTech
Жыл бұрын
@@fischi9129 you’re probably new to this or are extremely naive to think that you can just start using solid in prod for an actual product that is used by people. There’s literally not even 1/100th the support there is for react. React is well established and has been through its paces for years. I think solid is great I use it for quick projects, but there’s no way in hell I’m switching our established and stable codebase over, it’s such a terrible business decision. Neither will any other company.
F*ckn brilliance.
The fact that there is a question if it's bad and lots of time wasted by developers on figuring out how it should work tells that useEffect is not that good of a feature by design.
100% on the same line. It’s always funny to see that some developers on YT criticize Reacts core team dev work like if they were better ! 😂 Why they don’t join? 😂
@codewithguillaume
Жыл бұрын
At the same time, we can always do better… after others did something 😂
@vhaangol4785
Жыл бұрын
And many who defends React criticizes Angular, but similar to your statement, they aren't better than the Angular dev team. Criticisms are necessary because they give different perspectives on the subject thus allowing us to find further improvements, and as Theo always mentions, they make room for innovation.
@codewithguillaume
Жыл бұрын
@@vhaangol4785 absolutely my friend
@ninhdang1106
Жыл бұрын
Next time when you complain about a certain food, make sure you cook it yourself or else other people will say the same thing like you did "Why don't you cook it yourself?"
**useDefence**
Theo saying "git gut" at using useEffect, because this hook is just a SKILL ISSUE :) You do not know how it works, until you create your first infinite loop with it ;) Then reading the docs. Then you know :)
If I were useEffect I wouldn't feel very defended by this video. Summary of this video: useEffect is fugly (horrible interface for what it does), very obvious and tempting uses that all jr devs naturally adopt *that are footgun*, eh yeah it has its place for a couple narrow use cases - honestly seems like "never use useEffect, ever, unless you first consider 10 other options and then talk to a very very sr react dev" is good advice. Oh and official documentation is totally unclear about what the pitfalls are. A lot of dev best practices are about staying out of trouble and knowing how to do that, useEffect fails hard on that front as well. If I'm reading a PR there are a handful of things I'm always looking for and use of useEffect is one of those things I read and reread carefully and with a hefty default skepticism.
Am I the only person who sees no connection between hook names and their usage?
Anything with dependency arrays sucks in general
@ebrelus7687
Жыл бұрын
What is the reason I'm curious?
"Javascript runs"😅😅😅😅
7:14 "we don't give a second argument... if you want to run every time component renders" - really??? If you don't include a dependency array - then you get infinite loop BRO! So much for defense of useEffect() lol :D
@inakiarias7465
Жыл бұрын
Bro, you could have just typed the code into a React app and see that it doesn't create an infinite loop, it just runs the effect on every render call..
You should redo this video: kzread.info/dash/bejne/dXqso5eAnaevkrg.html. Last time you didn't even listen to the main points, instead just invented a straw man that you spent the entire video attacking. He makes very very good points about the use of useEffect. Ergonomics of useEffect are also silly of course and I agree with almost everything you mention, but the really dangerous issues with useEffect are about your "Please Do NOT useEffect For..." bullets .
♥️💯
i really dislike david ks talks lately for that reason. he brings up such bad examples and makes apples to pears comparisons just joking about how bad useEffect is. i too think its a powerful tool too many people misunderstand due to suboptimal api. but that doesnt make it inherently baf
Svelte does it better now (and faster)
@sumitpurohit8849
Жыл бұрын
But who uses svelte 😂😂
@sachahjkl
Жыл бұрын
@@sumitpurohit8849 talented people
@enyelsequeira3619
Жыл бұрын
@@sachahjkl said no one ever 😂
@sachahjkl
Жыл бұрын
@@enyelsequeira3619 ok dude, use whatever you want
@SamualN
Жыл бұрын
and solid does it even better (and even faster)
JS is the only language where this crap changes every 6 months. Hey, I'm a javascript dev lemme make sure I learn the same thing over and over again for marginal and debatable increases in DX or performance!
@eagsalazar
Жыл бұрын
boo hoo
@heroe1486
Жыл бұрын
You mean Js librairies? React haven't changed much since hooks
@thommccarthy1139
Жыл бұрын
@@heroe1486 patterns and practices. There's no tried and true consistent methodologies in JS development it's a free for all where whatever the top guy at x company believes, that's what you're doing. People shit on php but Laravel has clear patterns of development. You don't have ppl going on a 'well actually' rant every other day to dispute a concept's legitimacy.
First
React fanboy.
I feel like you guys live in a bubble where angular doesn't exist, but it exists, and it is so much better than react in certain ways.
I personally despise hooks 🪝
First