Mastering useEffect: Avoid Using useEffect!

แชร์
ฝัง
  • เผยแพร่เมื่อ 7 ก.พ. 2023
  • The most import rule with useEffect is to only use it when you really need it. This will greatly simplify your code and make it easier to maintain. Building maintainable codebases in React 18, NextJS or Remix is critical.
    #shorts
  • วิทยาศาสตร์และเทคโนโลยี

ความคิดเห็น • 95

  • @v.florio
    @v.florio ปีที่แล้ว +97

    Would be nice to explain why useEffect should be avoided

    • @ElektrykFlaaj
      @ElektrykFlaaj ปีที่แล้ว +20

      useEffect should not be used to set state, it should only do things that can't be done in any other way: subscribing to services and events, fetching data on component mount etc. Else it just gets complicated and hard to follow/maintain

    • @Dom-zy1qy
      @Dom-zy1qy 11 หลายเดือนก่อน +17

      @@ElektrykFlaaj True. For me i just know theres a linear coorelation between the amount of useEffects I use, and the amount of fuck-upery I end up coding.

    • @discontinuity
      @discontinuity 2 หลายเดือนก่อน

      @@ElektrykFlaaj In some cases, you need an effect to set the first state, initially.

    • @Rpkist77
      @Rpkist77 หลายเดือนก่อน

      @@discontinuity You don't need this either, just pass in the initial state as a prop, and use a key as another prop on that component that is set to that data. When that data changes, the component will be destroyed and recreated, causing it to use the prop as its initial value for the state variable.

  • @emmo2779
    @emmo2779 2 หลายเดือนก่อน +2

    an even better example is to use 's href

  • @hideinbush0
    @hideinbush0 ปีที่แล้ว +11

    I love these little clips. Thank you.

  • @tkdevlop
    @tkdevlop ปีที่แล้ว +30

    I guide you to the treasure that I myself can't possess

  • @aryandhakal7961
    @aryandhakal7961 10 หลายเดือนก่อน +1

    By the way, I really follow from top to bottom. You are a really great tutor. Teachers like you deserve great reach and applaud. It's strike to the point and most important is easy to understand the use of simple language so a person from not heavily English-speaking country can also understand you.
    Love and Respect from Nepal.

  • @PaulSebastianM
    @PaulSebastianM 7 หลายเดือนก่อน +2

    use Effect and callbacks or event handlers are side effects on a pure function. That's what most React developers don't get. They are ways to introduce side effects inside a pure system. One reacts to state, the other reacts to user input. Decide and chose.

  • @ogreeni
    @ogreeni ปีที่แล้ว +4

    I was waiting for this one!

  • @Crevulus
    @Crevulus ปีที่แล้ว

    Love these shorts - perfect for picking up tidbits while I'm out and about

  • @ozzolim
    @ozzolim ปีที่แล้ว +1

    I have learned a lot from you. Thank you

  • @maysamtayyeb4552
    @maysamtayyeb4552 ปีที่แล้ว +1

    Jack, you’re awesome. Dude 😊

  • @benaloney
    @benaloney ปีที่แล้ว +9

    Use react-query in this case...

  • @minhnhatnguyen8200
    @minhnhatnguyen8200 ปีที่แล้ว +2

    Wow i love this advice

  • @prashlovessamosa
    @prashlovessamosa 11 หลายเดือนก่อน +1

    Thanks for making this.

  • @avneet12284
    @avneet12284 ปีที่แล้ว +2

    David Khourshid has a whole talk on this that's unmissable

  • @beakerbkr
    @beakerbkr ปีที่แล้ว +1

    I love this so much

  • @user-tb4ig7qh9b
    @user-tb4ig7qh9b ปีที่แล้ว +1

    man where is this video before 3 months oh when you have a programmer in team do not know any thing but boss love it.

  • @meh6930
    @meh6930 ปีที่แล้ว +4

    Couldn’t agree with this one more. I’ve worked on so many convoluted code based where it’s a treasure hunt to find out what’s actually happening when some event triggers. Cringed hard in my last project where one of the “senior” devs had chained useEffects throughout the app

  • @oscardasilva971
    @oscardasilva971 ปีที่แล้ว +11

    Good one. But don't forget to wrap your function around useCallback hook so it won't be recreated every re render

    • @bluesbr09
      @bluesbr09 3 หลายเดือนก่อน

      Ackshually.. you shouldn’t. The only reason to use useCallback is to keep the function identity stable. By default, rerenders result in a new reference for the function. And the only reason you’d care about that is if you’re passing the function to a child as a prop, and don’t want the child to keep rerendering when the parent rerenders (due to the changed reference). useCallback doesn’t prevent the function from being “recreated”. That’s because the runtime can’t magically remember the function you passed to useCallback. When rerendering, and when the runtime hits the useCallback line of code, it still needs to run “useCallback(() => ..)”, and call it, and pass it the function. It’s just a function call with a function as a parameter. It still has to “create” the function that’s inside it, in order to pass it.
      Hope that clears it up!

  • @LocTran-sn3mp
    @LocTran-sn3mp ปีที่แล้ว +4

    Hello, thank you for your short sharing videos. May I ask you what theme are you using in those short videos? It looks so good

    • @jherr
      @jherr  ปีที่แล้ว +1

      JETBrains Mono.

  • @kazz94
    @kazz94 หลายเดือนก่อน +1

    What about the initial fetch? The fetch will no longer trigger when the component first renders.

  • @sc76399
    @sc76399 ปีที่แล้ว

    I mostly use it for umbrellas unrelated side effects or something on mount

  • @angelrodriguezsantiago627
    @angelrodriguezsantiago627 6 หลายเดือนก่อน +4

    I would rather avoid React in general

  • @waleedsharif618
    @waleedsharif618 ปีที่แล้ว +9

    This is good, could you show more examples?

  • @elrmndo
    @elrmndo ปีที่แล้ว +1

    This is gold

  • @yassinesafraoui
    @yassinesafraoui ปีที่แล้ว

    Only two use cases that are left are updating a component's state when its props change or running some code only when at the first run

  • @lautarocarreno3161
    @lautarocarreno3161 ปีที่แล้ว +1

    Now i feel more junior jajaja

  • @Its_RTS.
    @Its_RTS. หลายเดือนก่อน +1

    Fetching data is a side effect, and the useEffect hook in React is ideal for handling such effects. It's particularly well-suited for fetching data because useEffect allows you to clean up any in-flight requests. This helps prevent race conditions that might arise from rapid user clicks.

  • @aryandhakal7961
    @aryandhakal7961 10 หลายเดือนก่อน +1

    What if someone needs to auto-fetch data while rendering the screen? What you are doing is fetching the URL after the button is pressed right? So in the first cycle of component mount the URL won't be fetched right?

  • @JethiyaChampakGada
    @JethiyaChampakGada ปีที่แล้ว +1

    I tried it but if you set a state and accordingly fetch the state gets updated later and function gets executed first

  • @ankitpradhan4183
    @ankitpradhan4183 6 หลายเดือนก่อน +1

    you still had the url as props coming in though, so of you want to have the initial fetch to include the url, useEffect is MUST.
    useEffect is not bad if you know how to use it.
    Nowadays there are people shoulting use react query, apollo client etc etc etc. Sure Id use that and I am using that. But they too use useEffect.
    This whole dogma of useEffect being bad is just nonsense.
    in this example, you addressed one issue of handling calls from events but did not handle the props change , for that you would use useEffec anyway

  • @YusufSalahAdDin
    @YusufSalahAdDin ปีที่แล้ว +2

    How will the component be rerendered after the data is fetched then? Maybe there is something I'm not understanding well.

    • @yojou3695
      @yojou3695 ปีที่แล้ว +1

      you fetch and then you set data. Which is reactive due to useState. It will rerender

  • @marcusviniciussilvaoliveir8559
    @marcusviniciussilvaoliveir8559 ปีที่แล้ว

    But in a more complex component, if we have other states being updating besides the "url" state, without a useEffect, the component will fetch all the time without needing. In the first example with useEffect, we avoid unecessary re-fetch in other re-renders

    • @jherr
      @jherr  ปีที่แล้ว

      Why would it do that? We only invoke the fetch on a click.

  • @KamilDrozdz
    @KamilDrozdz ปีที่แล้ว +1

    Hi Jack, you have super movies, I loved watching them! But I have a question, what if we have an infinity scroll and we need to have some trigger for the URL change without pagination, will this method still work with the use of a callback?

    • @jherr
      @jherr  ปีที่แล้ว +4

      No, because you need a useEffect for that. I'm not saying to NEVER use useEffect. I'm just saying that if you can get away with not using it, then avoid it.

  • @Vitalik186
    @Vitalik186 ปีที่แล้ว +2

    The best way to use hooks is to avoid hooks :)

  • @itsanuragjoshi
    @itsanuragjoshi 8 หลายเดือนก่อน

    Please explain how will you re-render the component without useEffect on changing url in the example shared above?

  • @mnite3842
    @mnite3842 10 หลายเดือนก่อน

    in this case, avoiding useEffect means avoiding rerendering

  • @roxysingh4195
    @roxysingh4195 8 หลายเดือนก่อน

    Don't use useEffect for making dynamic functionality in a component over time, it can lead to a "re-render loop" or unexpected behavior". I only use it when I need to initiate the component with Some API data or the initial State based on previous interaction with the app or parent component. and UseEffect Sometimes become unavoidable too. you can always work around it but that can make thing messy.

  • @CFXTBogard
    @CFXTBogard ปีที่แล้ว +1

    Avoid the avoidable :D

  • @Dline8
    @Dline8 ปีที่แล้ว +2

    Is this all from a video or is it just a shorts series?

    • @jherr
      @jherr  ปีที่แล้ว +1

      The shorts I produce are their own thing, but I do have a lot of longer form videos on my React playlist about useEffect.

    • @Dline8
      @Dline8 ปีที่แล้ว

      @@jherr Okay thanks, I have to work with React professionally and your videos are a huge help. Thanks so much for taking the time to put out such helpful content like this. It's greatly appreciated!

    • @jherr
      @jherr  ปีที่แล้ว

      @@Dline8 I'm glad they work for you!

  • @killerdroid99
    @killerdroid99 4 หลายเดือนก่อน +1

    Avoid useEffect useLayoutEffect 😂😂

  • @taukirsheikh9405
    @taukirsheikh9405 ปีที่แล้ว

    I still processing , looks like i need to try it

    • @jherr
      @jherr  ปีที่แล้ว +1

      Trying it is really the only way to learn.

  • @pranupranav6279
    @pranupranav6279 ปีที่แล้ว +2

    useEffect with empty dependency array can do it.

    • @jherr
      @jherr  ปีที่แล้ว +2

      useEffect with an empty dependency array is the equivalent of not using a useEffect at all and simply putting the code in-line. The only difference is that the execution is postponed until after the render.
      In this simple example it would work. But that's only because the example is so simple and there is only one piece of state.

    • @pranupranav6279
      @pranupranav6279 ปีที่แล้ว

      ​​​@@jherr my main motive was to fetch the data and update the data state after the component is rendered as the url value is updated. I specifically came across this problem while working on a nextjs project where param was passed in url and rendering technique was ssr+csr, then using the param variable to make an API call and fetch data.
      Btw useEffect sometimes leads to bugs very hard too debug. I always follow and suggest use less useEffect.

  • @rjmunt
    @rjmunt ปีที่แล้ว

    I can imagine some use cases. Here, unless I'm mistaken there is no fetch call on mounting of the component?

    • @jherr
      @jherr  ปีที่แล้ว

      That is true. For that you do need a useEffect. Or just switch to react-query.

  • @aliensoul7600
    @aliensoul7600 ปีที่แล้ว +1

    I'm new to react.js. Sir your saying to avoid useEffect, Then what should i use sir?

    • @jherr
      @jherr  ปีที่แล้ว +1

      It's hard to avoid entirely. But there are often patterns other that don't involve useEffect. For example, like using something like React-Query or SWR to run fetch requests as opposed to using a useState/useEffect pattern.

  • @jiachen1078
    @jiachen1078 ปีที่แล้ว +1

    🎉I actually made this mistakes before!

  • @Cowkill
    @Cowkill ปีที่แล้ว +5

    You should use useEffect only if you need a visual change.

    • @jamesfoley4426
      @jamesfoley4426 ปีที่แล้ว

      Can you elaborate on that? Can you explain why please?

    • @crazyiron9003
      @crazyiron9003 ปีที่แล้ว

      ​@@jamesfoley4426 For example you have a filtering going on your app, and you want to make the state change. You then need to wrap it inside useeffect, then put the state that you want to change in the dependency array.

  • @Dylan_thebrand_slayer_Mulveiny
    @Dylan_thebrand_slayer_Mulveiny 8 หลายเดือนก่อน

    I think the golden rule of coding is this: If you're thinking of using a complex, hacky solution 99% of the time you're doing it wrong. Stop, take a step back and re-evaluate your options.

  • @vetrivendhan6122
    @vetrivendhan6122 11 หลายเดือนก่อน

    But, I can't avoid that useEffect completely. There are stone situations. Like React query on success events. They deprecated the onSuccess callback, so I have to use React query helper.isSuccess in the useEffect. I don't find a solution for that case.

  • @michaeldausmann6736
    @michaeldausmann6736 9 หลายเดือนก่อน

    I feel like you have chosen a very specific example to illustrate an approach that is not generalisable. In your example, I think that the component is still 'pure' i.e. it only fetches on click and you have not shown anything in the callback that might cause the component to re-render e.g. calling setData... in short, your callback as written has no side effects so yes, it is ok to avoid useEffect. This is not really the general use case of useEffect though. In most cases, you use useEffect to fetch data that *does* change the rendered component which is why the useEffect hook exists.

  • @FourLeafGroverRL
    @FourLeafGroverRL 9 หลายเดือนก่อน

    useEffect is a pain, if you have to use it, put it in a hook cause it just makes it nicer to work with in my opinion 😂

  • @DrClocktopus1
    @DrClocktopus1 ปีที่แล้ว

    Won't useCallback be a better option?

    • @jherr
      @jherr  ปีที่แล้ว

      Yes, in most cases you can use a callback instead of doing a reactive useEffect.

  • @petarkolev6928
    @petarkolev6928 ปีที่แล้ว

    This example is great and all but what happens when I'm using RTK Query and I need to execute a function based on the mutation's result? This can be done only in useEffect :/ which I hate doing... For example, I execute the mutation in the button handler which is normal but then I need to execute a method on mutation success, so I am listening for that mutation's success in the useEffect. Is there any other Reacty way of doing this? (besides state machine which I am not using in this project).

    • @jherr
      @jherr  ปีที่แล้ว +1

      I'm not saying never use useEffect. I'm saying choose a different mechanism with less risk if the option is available to you.

    • @petarkolev6928
      @petarkolev6928 ปีที่แล้ว

      @@jherr Hey, Jack :) I never assumed you suggest such thing :) Yesterday I had such issue where I am forced to use a callback in one of my useEffects which was very annoying and I didn't knew what to do differently so I left a comment in hope to get an answer :D

    • @jherr
      @jherr  ปีที่แล้ว +1

      @@petarkolev6928 No worries. I'm honestly surprised that there isn't a way to do that? It seems like a VERY obvious requirement for a state manager. Everything time we change this, also call that. It's super easy in Zustand, Valtio or Jotai.

    • @petarkolev6928
      @petarkolev6928 ปีที่แล้ว

      @@jherr I want to try xstate. I've watched your videos while ago explaining how good it is and what a gem is when it comes to triggering actions on a curtain event instead of putting all of that in useEffect :)

  • @alext5497
    @alext5497 ปีที่แล้ว

    I disagree about this being simpler or easier to maintain but it is the way to do it

  • @georgios_georgiou
    @georgios_georgiou ปีที่แล้ว +2

    But if you do that you change the requirements right? In the useEffect example the fetch will run when on mount (twice because of double render) and when url is updated while on the second one only on button click…
    I suggest custom hook for this to keep it aligned with requirements ❤

  • @brentryczak
    @brentryczak ปีที่แล้ว +1

    I’ve actually gone out of my way in cases to only make use effect the driving force of change on the component. Have no idea why. Now I cry.

  • @artemeelemann317
    @artemeelemann317 ปีที่แล้ว

    How then you cancel this requests in case of repetitive clicks? You always forget this in your videos, and then you can run into race conditions this way.

    • @jherr
      @jherr  ปีที่แล้ว

      Well, I do have to keep the code short. To avoid repetitive clicks you can disable the buttons on the initial fetch. Or you can debounce.

  • @Nioxs
    @Nioxs ปีที่แล้ว

    Well why tf would u want to use it, if you dont have a default url that u want to load on render O.o

  • @saadisaadi8199
    @saadisaadi8199 ปีที่แล้ว

    But useEffect should be used when calling browser apis, it's what react docs says?!!

    • @saadisaadi8199
      @saadisaadi8199 ปีที่แล้ว

      Besides what's the name of that font? It looks great

  • @MeAsMeButMe
    @MeAsMeButMe ปีที่แล้ว

    But why have you avoided it in the first place? This just shows how but the why is the most important thing in programming. But at the same time I'm drinking wine so maybe I missed something 🤣🍷

    • @jherr
      @jherr  ปีที่แล้ว +3

      Fair enough. The why is that IMHO, you should always try to write the safest, most reliable, most maintainable code possible. And useEffect has a ton of inherent risk. So when you can, avoid useEffect, because the risks of it can often be avoided by using a mechanism with less risk.
      Enjoy the wine!🍷

  • @randomuser1161
    @randomuser1161 10 หลายเดือนก่อน

    two twings. Why avoid useEffect? And by not changing the URL you lose the "going back and forth - navigation"-convenience :D

  • @shishirarora8808
    @shishirarora8808 ปีที่แล้ว

    What if you need to fetch when this component mounts?

  • @SithLordBishop
    @SithLordBishop ปีที่แล้ว +2

    Take it one step further and don't use react :D :D

  • @andrii6292
    @andrii6292 22 วันที่ผ่านมา

    Moreover, this function should not be a part of this component. This is a helper

  • @Wentris71
    @Wentris71 14 วันที่ผ่านมา

    Too obvious)