Why useEffect causes infinite loops - fix it with useCallback

แชร์
ฝัง
  • เผยแพร่เมื่อ 10 พ.ย. 2024

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

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

    thank you, been struggling here for 2 hours

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

    I'm not a react dev, just curious. However, this is a great programming tutorial because it shows the audience different angles to resolve the issue and evaluates them against use-cases. This is something neglected with many tutorial videos!

  • @zaidofficials
    @zaidofficials 18 วันที่ผ่านมา +1

    Beleive me this video cleared all my doubts on use callback use memory use effect
    Thank you so much

  • @CB4TS
    @CB4TS 2 ปีที่แล้ว

    I am glad I came across this video. I had been ignoring that warning because I didn't know what it meant, but after watching this video, now I can fix it. Thanks!

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

    Oh yes, just what I needed, thank you!! 👌

  • @mohammed.haydar
    @mohammed.haydar 2 ปีที่แล้ว

    I've been building a react app for a couple of months now, this problem has occurred a lot it's really irritating this video cleared it a little bit, but I need to apply it to my code to learn it 🙃

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

    Ooo we're definitely guilty of some of this over here! I like the idea of separating out api calls. It gets a little wild in there. Thanks for the breakdown!

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

      Yeah keeping them separate helps them also be reusable in other components if needed

  • @syamprasadupputalla8233
    @syamprasadupputalla8233 2 ปีที่แล้ว

    Thank you brother for bringing up this👏👏. I feel you should bring up all react topics in depth as you do. It would be helpful to everyone.🤝🤝

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

    Dude thank you. I had been using useEffect in some of my apps and was passing a state value in as a dependency in the dependencies array and wasn't understanding why api calls were getting made a million times. Definitely not a good thing when you can only make a limited number of api calls per month for certain apis lol. I was looking for how to stop this and had tried watching other videos but nobody was helping, so thank you 🙏

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

      Like I was watching the useEffect working with console logs and was like 🤬 here goes all my api calls

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

      Isn’t react great?!

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

    useCallback and useMemo do the same thing. They just remember the value and stop re-creating functions unnecessarily. The only difference is useCallback returns the entire function while useMemo runs the function and returns the result.

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

      Does that mean you can get the same functionality as useCallback when you pass a function that returns a function in useMemo?

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

    very very good video, thank you!

  • @cwancy
    @cwancy 2 ปีที่แล้ว

    Even though I don't use React in my dev job, your videos are just great and informative.

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

    I will try this solution tomorrow, am trying to fix it for multiple hours in my project and stopped to take a break.
    Hopefully it will work.

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

    Awesome! Just What I wanted.

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

    amazing explanation bro! thank you so much!

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

    I am working with React app atm and that lint warning for useEffect dependency is annoying. The first solution to move the code outside of component seemed to be the best and simplest imo.

  • @阿弘-n4f
    @阿弘-n4f ปีที่แล้ว

    This is very helpful! Thank you!

  • @Sky-yy
    @Sky-yy 2 ปีที่แล้ว

    Very good topic to pick.

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

    Great tutorial to the point thank you for your great explanation!!

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

    Not junk at all, I have just leant something important.thx.

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

    Which theme are you using?

    • @WebDevCody
      @WebDevCody  2 ปีที่แล้ว

      Shades of purple

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

    useCallback => use memory function
    useMemo => use memory value (calculator)

  • @ytaccount8374
    @ytaccount8374 2 ปีที่แล้ว

    Hi, great video! Thank you! I'm wondering... how do you get the errors on your editor window? e.g. the error (warning?) on 0:21.

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

    thank you!

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

    thank you a lot !!!

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

    I really appreciate the detail of your breakdown of the infinite loop with function dependencies. What are your thoughts on the case of returning an api fetch callback from a custom hook, which then gets called in useEffect (naturally this triggered the useEffect dependencies warning)? I can't figure out if there's any simple fix for this (or if my code setup is violating some fundamental React principles, haha). Thanks.

    • @WebDevCody
      @WebDevCody  2 ปีที่แล้ว

      I guess I’d ask why is the api fetch in a custom hook and not just a helper method? Are you setting isLoading state or something?

    • @paeon21
      @paeon21 2 ปีที่แล้ว

      ​@@WebDevCody It's funny, I jumped into making a custom hook without ever asked myself that before, but I've since incorporated both authContext and react-router into my hook for checking authentication on any api call (setting isAuth and authError states) and conditionally navigating to login.
      Does it sound like I should be extracting the api logic into a helper function, while refactoring the custom hook to focus just on auth handling?

    • @WebDevCody
      @WebDevCody  2 ปีที่แล้ว

      @@paeon21 I'd say all axios calls should be wrapped into their own helper functions. You'd use these functions from your components. I also don't think you should even be trying to make these requests unless you're authenticated, so if you have a component that tries to hit a secured endpoint on mount, you shouldn't be rendering it when not logged in.... join my discord, it's too hard to help via yt comments

    • @paeon21
      @paeon21 2 ปีที่แล้ว

      @@WebDevCody Cool. Will do. Thanks.

  • @mohiuddinshahrukh
    @mohiuddinshahrukh 2 ปีที่แล้ว

    Generic feedback,
    1. close the left tab
    2. Please dont move the screen (scroll) so much its dizzying!

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

    Very good content ❤ u bro.

  • @okopyl
    @okopyl 2 ปีที่แล้ว

    Please, leave the link to the code's repo so everyone can check whether or not the code in your video works or not.
    In my example it does not, since I'm not getting the same warning you do.

  • @tnsaturday
    @tnsaturday 2 ปีที่แล้ว

    BTW, you don't want to use useCallback with your API requests, because it assumes your function is pure, that means it always returns the same result given the same input. But if something happened on the server side and the object you're fetching has changed (like someone patched or deleted the resource), you're not making the request because the response have been cached and you have no way of finding that out.

    • @WebDevCody
      @WebDevCody  2 ปีที่แล้ว

      That’s incorrect. UseCallback caches the function reference. Try it out. Make an api that increments by one each request and do this same approach on the UI with useCallback. You’ll get a new number each time. Also, where does it say in the react docs useCallback assumes a pure function? It doesn’t.

    • @tnsaturday
      @tnsaturday 2 ปีที่แล้ว

      @@WebDevCody Maybe I mistaked it with useMemo, I'll give it a try, thank you.

    • @WebDevCody
      @WebDevCody  2 ปีที่แล้ว

      @@tnsaturday yeah you’re correct, use memo will cache the value

  • @소중한-u5o
    @소중한-u5o ปีที่แล้ว

    this is useful vidoe!

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

    Also keeping the dependency array empty fixes this issue.

  • @ahmrfjamali7958
    @ahmrfjamali7958 2 ปีที่แล้ว

    Best solution is useQuery or use custom hooks

  • @SeibertSwirl
    @SeibertSwirl 2 ปีที่แล้ว

    Good job babe!!!! FIRST!!!!!!

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

      Shucks do you have super powers!? I was so quick to see this one!! ONA THESE DAYSS!!

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

      Bahahahaha neverrrrrr!!!!!!!

  • @coldym
    @coldym 2 ปีที่แล้ว

    Ohh I like this over engineered stuff from react

  • @bensonyeboah297
    @bensonyeboah297 2 ปีที่แล้ว

    great

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

    There is another solution the `useEffectEvent`

  • @okopyl
    @okopyl 2 ปีที่แล้ว

    Why recreating a function reinvokes useEffect?
    The reference to the function remains the same, meaning getPokemon === getPokemon

    • @rea1m_
      @rea1m_ 2 ปีที่แล้ว

      Actually after re-render getPokemon function will have a new reference

    • @okopyl
      @okopyl 2 ปีที่แล้ว

      @@rea1m_ why?

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

      @@okopyl cuz it recreates the whole component. useCallback preserves the reference and only gets a new one when dependencies change. Go check it out yourself.

    • @okopyl
      @okopyl 2 ปีที่แล้ว

      @@rea1m_ thanks

  • @tnsaturday
    @tnsaturday 2 ปีที่แล้ว

    React functional components are so complicated compared to Vue clearness.

    • @WebDevCody
      @WebDevCody  2 ปีที่แล้ว

      that I will agree with. these hooks make things twice as hard to understand.

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

      @@WebDevCody Agreed, I'm used to work with Vue and just using React for a project, these hooks concept seems easy on docs, but pretty hard to use properly on practice. But I'm wondering, these hooks are there to enable us to optimize how the component works, right? What about Vue, is it able to optimize by itself or what?

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

    i tried doing this ````const [dataone, setdataone] = useState([]);
    const [datatwo, setdatatwo] = useState([]);
    const fetchMovies = async () => {
    const response = await Promise.all([
    axios.get("url"),
    axios.get("url"),
    ]);
    console.log(response)
    setdataone(response[0])
    setdatatwo(response[0])
    conosole.log(dataone)

    },
    useEffect(() => {
    fetchMovies();
    }, []);```
    console.log(dataone) is logging an empty array but console.log(response) logs out the data can some one help

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

      setter function provided by useState does not set the value right away. when you call it in somewhere in the code React schedules a re-render of the component with the newly set value. So dataone actually reflects the value in the following re-render. you can clearly see this if you take the console.log(dataone) out of the fetchMovie function.
      you will see two logs, one with an empty array (your initial value) and the other with data.

  • @dailymeow3283
    @dailymeow3283 2 ปีที่แล้ว

    Best work around might be Next js, fetch the pokemons in getStaticProps then pass em to the page as prop

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

      That will work as well and is a good solution, but it won’t solve every issue if your app needs to dynamically fetch data. You’ll eventually run into this same issue if you’re using a linter that wants the useEffect deps array.