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.
@karixening2 жыл бұрын
EXACTLY, like if you want to add and remove an event listener. Otherwise you'd have to memoize the function reference.
@lukeyd132 жыл бұрын
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
@inwerpsel2 жыл бұрын
@@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.
@skyhigheagleer62 жыл бұрын
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
@hunterwilhelm2 жыл бұрын
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
@TypingHazard2 жыл бұрын
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
@kimbapslayer19952 жыл бұрын
Easy videos for creators. Basically lazy easy money
@RudraSingh-pb5ls2 жыл бұрын
@@hunterwilhelm hope theo isn't teaching useEffects the traditional way
@zygote3964 ай бұрын
the example about doubleCount is especially absurd. just derive/compute the value, no need for state! idk about you but i have never encountered a situation like the doubleCount scenario, however I have to update state from useEffects all the time. it's not that you shouldn't do it, it's that you have to be very thoughtful about your dependencies and ensure you have proper conditions to prevent infinite loops, none of which you can be taught by incrementing an integer by 1.
@omminnoremac2 жыл бұрын
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.
@hunterwilhelm2 жыл бұрын
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
@samuelgunter2 жыл бұрын
@@hunterwilhelm deps shouldn't go there incase the synchronous effect takes long
@brettstoddard79472 жыл бұрын
could that be passed around with a setstate?
@niroren64532 жыл бұрын
in addition, there is also an implicit behavior of passing an empty deps array [] has a special meaning of run once
@kostabrillakis362 жыл бұрын
It’s amazing that we get these free videos where a senior developer discusses this information. Big fan of Theo
@MrAssassin98912 жыл бұрын
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.
@TheChodex2 жыл бұрын
My main issue with useEffect is that it feels like it doesn't really adhere to the single responsibility principle.
@Davidlavieri2 жыл бұрын
that's why you use múltiple ?
@haaxor1689 Жыл бұрын
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).
@seannewell3972 жыл бұрын
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.
@kimbapslayer19952 жыл бұрын
Wtf are you saying
@m__c_s Жыл бұрын
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
@aerocodes2 жыл бұрын
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
@jussinevavuori25982 жыл бұрын
Can you show an example? A github link or something?
@aeroprojects8 ай бұрын
I never have the feeling of wasting my time on this channel, learning new things every time 👍 Thanks Theo
@kevinliao50212 жыл бұрын
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👍
@igorordecha2 жыл бұрын
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.
@jeffreydelossantos86675 ай бұрын
for cleanup, useEffect should be used merely for side effects. and it runs after rendering
@mil0s2512 жыл бұрын
So how would one fetch data on component mount without useEffect and without any third party libraries?
@MrHamsterbacke7562 жыл бұрын
You can't
@mil0s2512 жыл бұрын
@@MrHamsterbacke756 then is that a bollocs he says in the vid?
@ebrelus76872 жыл бұрын
And how such library does it? Is it the only hook of power?
@zombiefacesupreme2 жыл бұрын
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.
@DanDelarge2 жыл бұрын
"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 😂
@ParshuramNPatil872 жыл бұрын
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.
@austincodes2 жыл бұрын
I remember writing HOC before hooks🥶
@codewithguillaume2 жыл бұрын
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? 😂
@codewithguillaume2 жыл бұрын
At the same time, we can always do better… after others did something 😂
@vhaangol47852 жыл бұрын
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.
@codewithguillaume2 жыл бұрын
@@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?"
@DevlogBill2 жыл бұрын
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.
@Remiwi-bp6nw9 ай бұрын
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
@alanhettinger40512 жыл бұрын
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)
@bernardoquina2 жыл бұрын
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.
@hunterwilhelm2 жыл бұрын
It’s a complicated function it should have a complicated name
@ebrelus76872 жыл бұрын
Can you add examples? Or is it like reduce vs other ho functions?
@miscany2 жыл бұрын
But I love using useEffect for update chains :) until I have to work on the project next week.
@drewhjava2 жыл бұрын
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
@uziboozy45402 жыл бұрын
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 🤦♂️
@BosonCollider Жыл бұрын
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
@DevlogBill2 жыл бұрын
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!
@Joao-nn6gn2 жыл бұрын
Wait, dont't useEffect for data fetching ? Where am I supposed to making my data fetching ? '-'
@zayn86492 жыл бұрын
If I'm not supposed to use useEffect for data fetching, what's the alternative?
@alanhoff892 жыл бұрын
"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.
@ebrelus76872 жыл бұрын
Which libraries have such "feature"?
@bisark12 жыл бұрын
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?
@NickServ2 жыл бұрын
"You could argue useQuery should be built into React at this point" Damn the foreshadowing here! 🤯
@rumplstiltztinkerstein2 жыл бұрын
In summary. Never deny the advantages a good hook can bring you at the right time.
@dagonzalez17572 жыл бұрын
Doesn't the clean up function also run on every rerender?
@MrHamsterbacke7562 жыл бұрын
No
@Davidlavieri2 жыл бұрын
Only if the dependencies changes
@guygolan36852 жыл бұрын
i want to fetch data and not use external library such as react-query and such. how do i do that with pure react?
@jackwakeham18082 жыл бұрын
Use fetch inside a useEffect or callback. Await the data and add it to state using useState. Then render the data however you like.
@mumu26922 жыл бұрын
checkout web dev junkie, theres a video talk about ur question
@michalzarddev2 жыл бұрын
useEffect(()=>fetch("api").then("extract data here"),["leave this empty is just wanna run it once on route/component loaded"])
@guygolan36852 жыл бұрын
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?
@oscarljimenez57172 жыл бұрын
@@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.
@origanami Жыл бұрын
Just overheard a conversation in my team: "Any opportunity you can take to remove useEffect do it, it just makes everything better"
@GG-uz8us2 жыл бұрын
Do you think hooks are actually just facade on top of components?
@SamyarBorder2 жыл бұрын
I just love your videos
@oleksandrfomin3262 жыл бұрын
Astonishing abstract thinking skills. I wish I had a brain that big lol
@guseynismayylov194510 ай бұрын
Am I a crazy, or nobody knows about template element in HTML?
@eagsalazar2 жыл бұрын
Proposed new title: "Hooks good, useEffect is a dangerous and awful abomination that should be replaced with a saner hook ASAP"
@keenanjet78792 жыл бұрын
Great energy !
@Slink12 жыл бұрын
Why are you not talking about just.js?
@codeChuck7 ай бұрын
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 :)
@eagsalazar2 жыл бұрын
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.
@coolemur976 Жыл бұрын
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.
@Ca-rp7bv2 жыл бұрын
Good points as always
@bigpimpinA12 жыл бұрын
Not me using useEffect for fetching data😎
@matowang2 жыл бұрын
Are render props considered bad practice? Isn't this the whole architecture of headless UI?
@MrHamsterbacke7562 жыл бұрын
You don't need the render props pattern for the most cases anymore
@ebrelus76872 жыл бұрын
@@MrHamsterbacke756 When that's still needed?
@fischi91292 жыл бұрын
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...
@OryginTech2 жыл бұрын
Ain’t nobody got time for that. The way it is, is perfect lol
@fischi91292 жыл бұрын
@@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 :)
@OryginTech2 жыл бұрын
@@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 💀
@fischi91292 жыл бұрын
@@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.
@OryginTech2 жыл бұрын
@@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.
@RicoCollins2 жыл бұрын
F*ckn brilliance.
@peopledrivemecrazy2 жыл бұрын
**useDefence**
@inasuma81802 жыл бұрын
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?
@DubiousNachos2 жыл бұрын
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
@nanohedron2 жыл бұрын
Am I the only person who sees no connection between hook names and their usage?
@sachahjkl2 жыл бұрын
Svelte does it better now (and faster)
@sumitpurohit88492 жыл бұрын
But who uses svelte 😂😂
@sachahjkl2 жыл бұрын
@@sumitpurohit8849 talented people
@enyelsequeira36192 жыл бұрын
@@sachahjkl said no one ever 😂
@sachahjkl2 жыл бұрын
@@enyelsequeira3619 ok dude, use whatever you want
@SamualN2 жыл бұрын
and solid does it even better (and even faster)
@eagsalazar2 жыл бұрын
You should redo this video: kzbin.info/www/bejne/eXfbcmh9oql8mLc. 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 .
@richard-social81252 жыл бұрын
"Javascript runs"😅😅😅😅
@AlexSpieslechner2 жыл бұрын
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
@go3712112 жыл бұрын
Anything with dependency arrays sucks in general
@ebrelus76872 жыл бұрын
What is the reason I'm curious?
@esabaliauskas2 жыл бұрын
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
@inakiarias74652 жыл бұрын
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..
@mprasanth182 жыл бұрын
♥️💯
@thommccarthy11392 жыл бұрын
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!
@eagsalazar2 жыл бұрын
boo hoo
@heroe14862 жыл бұрын
You mean Js librairies? React haven't changed much since hooks
@thommccarthy11392 жыл бұрын
@@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.
@NeuralNotes692 жыл бұрын
React fanboy.
@jonathangamble2 жыл бұрын
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.