In Defense Of useEffect - React's Most Dangerous Hook

Поделиться
HTML-код
  • Опубликовано: 23 ноя 2024

Комментарии • 131

  • @skyhigheagleer6
    @skyhigheagleer6 2 года назад +158

    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
      @hunterwilhelm 2 года назад +5

      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
      @TypingHazard 2 года назад +4

      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
      @kimbapslayer1995 2 года назад +7

      Easy videos for creators. Basically lazy easy money

    • @RudraSingh-pb5ls
      @RudraSingh-pb5ls 2 года назад

      @@hunterwilhelm hope theo isn't teaching useEffects the traditional way

    • @zygote396
      @zygote396 5 месяцев назад

      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.

  • @inwerpsel
    @inwerpsel 2 года назад +56

    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
      @karixening 2 года назад +4

      EXACTLY, like if you want to add and remove an event listener. Otherwise you'd have to memoize the function reference.

    • @lukeyd13
      @lukeyd13 2 года назад

      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
      @inwerpsel 2 года назад

      ​@@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.

  • @omminnoremac
    @omminnoremac 2 года назад +36

    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
      @hunterwilhelm 2 года назад +2

      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
      @samuelgunter 2 года назад +6

      @@hunterwilhelm deps shouldn't go there incase the synchronous effect takes long

    • @brettstoddard7947
      @brettstoddard7947 2 года назад

      could that be passed around with a setstate?

  • @MrAssassin9891
    @MrAssassin9891 2 года назад +11

    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.

  • @niroren6453
    @niroren6453 2 года назад +2

    in addition, there is also an implicit behavior of passing an empty deps array [] has a special meaning of run once

  • @kostabrillakis36
    @kostabrillakis36 2 года назад +5

    It’s amazing that we get these free videos where a senior developer discusses this information. Big fan of Theo

  • @haaxor1689
    @haaxor1689 Год назад +1

    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).

  • @TheChodex
    @TheChodex 2 года назад +7

    My main issue with useEffect is that it feels like it doesn't really adhere to the single responsibility principle.

    • @Davidlavieri
      @Davidlavieri 2 года назад

      that's why you use múltiple ?

  • @m__c_s
    @m__c_s Год назад +1

    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

  • @aerocodes
    @aerocodes 2 года назад +6

    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
      @jussinevavuori2598 2 года назад

      Can you show an example? A github link or something?

  • @seannewell397
    @seannewell397 2 года назад +2

    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.

  • @DanDelarge
    @DanDelarge 2 года назад +2

    "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 😂

  • @mil0s251
    @mil0s251 2 года назад +4

    So how would one fetch data on component mount without useEffect and without any third party libraries?

    • @MrHamsterbacke756
      @MrHamsterbacke756 2 года назад

      You can't

    • @mil0s251
      @mil0s251 2 года назад

      @@MrHamsterbacke756 then is that a bollocs he says in the vid?

    • @ebrelus7687
      @ebrelus7687 2 года назад

      And how such library does it? Is it the only hook of power?

  • @ParshuramNPatil87
    @ParshuramNPatil87 2 года назад +1

    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.

  • @zombiefacesupreme
    @zombiefacesupreme 2 года назад +9

    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.

  • @Joao-nn6gn
    @Joao-nn6gn 2 года назад +1

    Wait, dont't useEffect for data fetching ? Where am I supposed to making my data fetching ? '-'

  • @igorordecha
    @igorordecha 2 года назад +5

    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
      @jeffreydelossantos8667 5 месяцев назад +1

      for cleanup, useEffect should be used merely for side effects. and it runs after rendering

  • @Remiwi-bp6nw
    @Remiwi-bp6nw 10 месяцев назад

    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

  • @aeroprojects
    @aeroprojects 9 месяцев назад

    I never have the feeling of wasting my time on this channel, learning new things every time 👍 Thanks Theo

  • @kevinliao5021
    @kevinliao5021 2 года назад

    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👍

  • @miscany
    @miscany 2 года назад +2

    But I love using useEffect for update chains :) until I have to work on the project next week.

  • @DevlogBill
    @DevlogBill 2 года назад +1

    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
      @Valyssi 2 года назад

      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.

  • @austincodes
    @austincodes 2 года назад +1

    I remember writing HOC before hooks🥶

  • @drewhjava
    @drewhjava 2 года назад +2

    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
      @uziboozy4540 2 года назад +1

      The problem with React is that it's so widely adopted.
      People should really stop using that garbage.

    • @Toulkun
      @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
      @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
    @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

  • @zayn8649
    @zayn8649 2 года назад

    If I'm not supposed to use useEffect for data fetching, what's the alternative?

  • @DevlogBill
    @DevlogBill 2 года назад

    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!

  • @bernardoquina
    @bernardoquina 2 года назад +8

    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
      @hunterwilhelm 2 года назад

      It’s a complicated function it should have a complicated name

    • @ebrelus7687
      @ebrelus7687 2 года назад

      Can you add examples? Or is it like reduce vs other ho functions?

  • @alanhettinger4051
    @alanhettinger4051 2 года назад

    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)

  • @NickServ
    @NickServ 2 года назад

    "You could argue useQuery should be built into React at this point" Damn the foreshadowing here! 🤯

  • @rumplstiltztinkerstein
    @rumplstiltztinkerstein 2 года назад +1

    In summary. Never deny the advantages a good hook can bring you at the right time.

  • @alanhoff89
    @alanhoff89 2 года назад +1

    "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
      @ebrelus7687 2 года назад

      Which libraries have such "feature"?

  • @bisark1
    @bisark1 2 года назад

    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?

  • @GG-uz8us
    @GG-uz8us 2 года назад

    Do you think hooks are actually just facade on top of components?

  • @guseynismayylov1945
    @guseynismayylov1945 11 месяцев назад

    Am I a crazy, or nobody knows about template element in HTML?

  • @dagonzalez1757
    @dagonzalez1757 2 года назад +1

    Doesn't the clean up function also run on every rerender?

  • @guygolan3685
    @guygolan3685 2 года назад +1

    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
      @jackwakeham1808 2 года назад +1

      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
      @mumu2692 2 года назад +2

      checkout web dev junkie, theres a video talk about ur question

    • @michalzarddev
      @michalzarddev 2 года назад

      useEffect(()=>fetch("api").then("extract data here"),["leave this empty is just wanna run it once on route/component loaded"])

    • @guygolan3685
      @guygolan3685 2 года назад +1

      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
      @oscarljimenez5717 2 года назад

      @@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.

  • @SamyarBorder
    @SamyarBorder 2 года назад

    I just love your videos

  • @origanami
    @origanami Год назад

    Just overheard a conversation in my team: "Any opportunity you can take to remove useEffect do it, it just makes everything better"

  • @oleksandrfomin326
    @oleksandrfomin326 2 года назад

    Astonishing abstract thinking skills. I wish I had a brain that big lol

  • @eagsalazar
    @eagsalazar 2 года назад

    Proposed new title: "Hooks good, useEffect is a dangerous and awful abomination that should be replaced with a saner hook ASAP"

  • @coolemur976
    @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.

  • @bigpimpinA1
    @bigpimpinA1 2 года назад

    Not me using useEffect for fetching data😎

  • @codeChuck
    @codeChuck 7 месяцев назад

    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 :)

  • @keenanjet7879
    @keenanjet7879 2 года назад

    Great energy !

  • @fischi9129
    @fischi9129 2 года назад +1

    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
      @OryginTech 2 года назад

      Ain’t nobody got time for that. The way it is, is perfect lol

    • @fischi9129
      @fischi9129 2 года назад

      @@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
      @OryginTech 2 года назад

      @@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
      @fischi9129 2 года назад

      @@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
      @OryginTech 2 года назад +1

      @@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.

  • @Ca-rp7bv
    @Ca-rp7bv 2 года назад

    Good points as always

  • @codewithguillaume
    @codewithguillaume 2 года назад +2

    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
      @codewithguillaume 2 года назад +2

      At the same time, we can always do better… after others did something 😂

    • @vhaangol4785
      @vhaangol4785 2 года назад +6

      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
      @codewithguillaume 2 года назад

      @@vhaangol4785 absolutely my friend

    • @ninhdang1106
      @ninhdang1106 2 года назад +1

      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?"

  • @Slink1
    @Slink1 2 года назад

    Why are you not talking about just.js?

  • @matowang
    @matowang 2 года назад

    Are render props considered bad practice? Isn't this the whole architecture of headless UI?

    • @MrHamsterbacke756
      @MrHamsterbacke756 2 года назад +2

      You don't need the render props pattern for the most cases anymore

    • @ebrelus7687
      @ebrelus7687 2 года назад

      @@MrHamsterbacke756 When that's still needed?

  • @inasuma8180
    @inasuma8180 2 года назад

    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
      @DubiousNachos 2 года назад +1

      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

  • @go371211
    @go371211 2 года назад +2

    Anything with dependency arrays sucks in general

    • @ebrelus7687
      @ebrelus7687 2 года назад

      What is the reason I'm curious?

  • @sachahjkl
    @sachahjkl 2 года назад +12

    Svelte does it better now (and faster)

    • @sumitpurohit8849
      @sumitpurohit8849 2 года назад +1

      But who uses svelte 😂😂

    • @sachahjkl
      @sachahjkl 2 года назад +1

      @@sumitpurohit8849 talented people

    • @enyelsequeira3619
      @enyelsequeira3619 2 года назад +1

      @@sachahjkl said no one ever 😂

    • @sachahjkl
      @sachahjkl 2 года назад

      @@enyelsequeira3619 ok dude, use whatever you want

    • @SamualN
      @SamualN 2 года назад +4

      and solid does it even better (and even faster)

  • @nanohedron
    @nanohedron 2 года назад

    Am I the only person who sees no connection between hook names and their usage?

  • @eagsalazar
    @eagsalazar 2 года назад

    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.

  • @RicoKareem
    @RicoKareem 2 года назад

    F*ckn brilliance.

  • @peopledrivemecrazy
    @peopledrivemecrazy 2 года назад

    **useDefence**

  • @esabaliauskas
    @esabaliauskas 2 года назад

    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
      @inakiarias7465 2 года назад +2

      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..

  • @richard-social8125
    @richard-social8125 2 года назад

    "Javascript runs"😅😅😅😅

  • @eagsalazar
    @eagsalazar 2 года назад

    You should redo this video: ruclips.net/video/CFxA5GmDIbU/видео.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 .

  • @mprasanth18
    @mprasanth18 2 года назад

    ♥️💯

  • @AlexSpieslechner
    @AlexSpieslechner 2 года назад

    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

  • @thommccarthy1139
    @thommccarthy1139 2 года назад +2

    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
      @eagsalazar 2 года назад +1

      boo hoo

    • @heroe1486
      @heroe1486 2 года назад

      You mean Js librairies? React haven't changed much since hooks

    • @thommccarthy1139
      @thommccarthy1139 2 года назад

      @@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.

  • @NeuralNotes69
    @NeuralNotes69 2 года назад

    React fanboy.

  • @jonathangamble
    @jonathangamble 2 года назад

    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.

  • @Dresmor
    @Dresmor 2 года назад

    First

  • @kahnfatman
    @kahnfatman 2 года назад

    I personally despise hooks 🪝

  • @sinanyaman2007
    @sinanyaman2007 2 года назад

    First