Avoid this React State Mistake | React Previous State Explained

Поділитися
Вставка
  • Опубліковано 18 гру 2024

КОМЕНТАРІ • 98

  • @DaveGrayTeachesCode
    @DaveGrayTeachesCode  3 роки тому +16

    Previous state is a powerful tool for working with React. And as with any tool, you need to understand when and how to use it for the best results. Updating state like the example setCount(count + 1) is not wrong and is even displayed in the React JS docs more than once. That said, it does not work in all situations, and it is easy to see why the preferred way for many is to always use a previous state function. If you are just getting started with React, I recommend my full 9 hour React course tutorial found here: ua-cam.com/video/RVFAyFWO4go/v-deo.html

    • @siddhartha0s01
      @siddhartha0s01 3 роки тому +1

      Thanks for the video Dave. I was playing around with this code and found that the counter works fine even if I use setCount(count => count+1) in a for loop or multiple times. Here I didnt use prev.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +6

      @@siddhartha0s01 you can name the parameter of the function whatever you want, prev, count, number, or any other word. It still represents the previous count. If you don't provide the function and just provide the setCount(count + 1) where count is your state, you cannot use it multiple times in the same function. I hope that helps explain.

    • @siddhartha0s01
      @siddhartha0s01 3 роки тому +2

      @@DaveGrayTeachesCode thanks for the clarification.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +2

      @@siddhartha0s01 you're welcome! 🙏

  • @carsugarmodels
    @carsugarmodels 2 роки тому +22

    The key phrase that explained everything "React updates state in batches". One another fantastic explanation from Dave. Thanks again!

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +1

      You're welcome!

    • @sfp2290
      @sfp2290 2 роки тому +1

      I completely agree. That line alone made me understand the rest (at least I assume I did).

    • @chrisstucker1813
      @chrisstucker1813 Рік тому +1

      Yeah it’s also worth knowing that “prev” is accessing the state directly from React’s internals which is updated every time you use setCount() - even if they’re hasn’t been a re-render.
      So in other words, doing setCount(count + 1) twice is indeed setting React’s internal state array to 2; however you need “prev” to access this internal state because the outer state identifier “count” is outdated.

  • @tankashing
    @tankashing 3 роки тому +3

    wow, i'm all the way from Malaysia, watched this video and thought to myself "finally, something i always was confused about, explained to me easily". Thank you soso much :)

  • @GabrielMartinez-ez9ue
    @GabrielMartinez-ez9ue 3 роки тому +1

    exactly the lecture i needed. incredible! i saw the exact same docs in reacts website and still could not understand when to use the previous state.

  • @mostinho7
    @mostinho7 Рік тому +1

    Done thanks
    Always use the version of state setter that takes the previous value because just setting the state without taking previous value doesn’t behave properly

  • @stillsmart
    @stillsmart Рік тому

    That helped clarify a few important notions. Thank you!

  • @funnyway683
    @funnyway683 Рік тому +1

    Thank you Dave ! you helped me having a better understanding of states in React

  • @caffeinated-pixels
    @caffeinated-pixels 3 роки тому +6

    Nice explanation Dave, this is definitely one of those state pitfalls that tend to confuse beginners.

  • @ahmad-murery
    @ahmad-murery 3 роки тому +2

    Updating the state using previous value did tricked me for a moment as I wasn't aware of it,
    it's hard to forget what was learned from a mistake (my life story 🤦‍♂️)
    Thanks for the update Dave,

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +2

      Good to hear from you, Ahmad, and I agree! Mistakes are a valuable teacher, and I have learned a lot from them.

    • @ahmad-murery
      @ahmad-murery 3 роки тому +1

      @@DaveGrayTeachesCode it's been a really tough days for me lately, but even so I enjoyed watching and liking your 2 previous videos, unfortunately I couldn't comment on them with an empty mind.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +3

      @@ahmad-murery I understand my friend. Hang in there. I appreciate the support!

  • @jackiefranken590
    @jackiefranken590 2 роки тому

    Thanks!

  • @sameembanu2077
    @sameembanu2077 5 місяців тому

    As usual,dave is great.

  • @jamshidtashkent1976
    @jamshidtashkent1976 Рік тому

    Good lesson. Thank you. I'm trying to understand the lessons from the first lesson. Sometimes it is hard to get it but the next lessons seem very easy.

  • @jackiefranken590
    @jackiefranken590 2 роки тому

    Dave you just saved my demo. God bless

  • @annemieknieboer8221
    @annemieknieboer8221 2 роки тому

    Thank you so much for this clear explanation, you are a hero! Needed previous state for adding items to an array and got it working immediately after watching your tutorial 👏🥳

  • @ohmygoodness6773
    @ohmygoodness6773 Рік тому

    Thank you that was very detailed and helpful

  • @avidambassador6665
    @avidambassador6665 3 роки тому

    Great video, helped clear misconceptions with state. Cheers.

  • @houseofcoding101
    @houseofcoding101 2 роки тому

    thank you soo much dave. Great Explanation!

  • @matinsasan
    @matinsasan 2 роки тому

    Thanks for clarifying how state update works, Dave.

  • @lugh5188
    @lugh5188 Рік тому

    Great video and explanation.

  • @ibrahimacanada
    @ibrahimacanada 2 роки тому

    Great course very clear !!

  • @muratalpersarisoy9104
    @muratalpersarisoy9104 Рік тому

    Great, finally understood :) Thanks

  • @0x0abb
    @0x0abb 2 роки тому

    Thank you Dave for your awareness 🤩

  • @vivarantx
    @vivarantx 2 роки тому

    great video my boy, thanks for helping a brother out

  • @umeshpalsingh9391
    @umeshpalsingh9391 2 роки тому

    Thank you so much, Know I understand how prevState works

  • @cuberos7430
    @cuberos7430 Рік тому

    How the same,This simple awesome explanation .Gray You are Great !!

  • @bewildstudio
    @bewildstudio 2 роки тому

    Very clear... thank you)

  • @oussemabouyahia474
    @oussemabouyahia474 Рік тому

    perfect content , thank you a lot for sharing knowledges

  • @mici2567
    @mici2567 2 роки тому

    Super video thanks !

  • @onlyhasbi
    @onlyhasbi 2 роки тому

    Thanks Dave 👍

  • @webpro607
    @webpro607 2 роки тому +2

    Great explanation!... I suggest you create an Udemy courses about React and JS... Subscribed to your channel 👏

  • @suprabhatkumar5478
    @suprabhatkumar5478 3 роки тому +1

    great video

  • @mohinderlamba
    @mohinderlamba 3 роки тому

    In the example where you update the object’s lastname property, if you update the firstname right after updating lastname without using previous value you will probably not get the lastname updated

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +1

      You are correct. This part of the video is at 10:04. You would need to pass the previous value function so you would have the lastname value you just updated before. However, if you were going to update both the first and last values in the example given, there would be no need for the previous state. If other properties existed, you would need the previous state.

  • @nos44-
    @nos44- 2 роки тому

    nice explanation ... but i was looking for the answer to WHY .. WHY and HOW prev state does what it does and WHY the currvalue doesnt work

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +2

      I thought I did explain that. When looking at WHY, it helps to understand closures. Whatever value the state has when the component renders is the value it will have no matter how many times you put setCount(count + 1) in your component - count will always have the same value. However, if you use the optional function parameter of setState like setCount(prev => prev + 1) the prev parameter is not assigned a value when the component renders - and that means it can update accurately each time you call it within the component. And you can call the prev parameter of the function curr or currVal or whatever you want to name it - it will still work the same.

    • @nos44-
      @nos44- 2 роки тому

      @@DaveGrayTeachesCode wow thanks for the quick response sir... Much appreciated ..
      Sorry if I missed the part .. m very new to react .. m just exploring random videos on YT ..but surely you explained it just the way I wanted it... Only reason I commented ...
      Thanks for everything

  • @RD-jr8nv
    @RD-jr8nv Рік тому

    Yo, totally different subject. Just a thought, by rearranging the open and close bracket of your logo, you could form the letter types D G. I.e. the closing one first, and the open second.

  • @Bskater952
    @Bskater952 3 роки тому

    Hey, first I just saw your playlists and they look great. I plan to watch all the videos available, but I was wondering, after learning react what's the point of using vanilla JS in projects instead of react?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +1

      Good question! You can use whichever you like best. JavaScript powers all of the libraries and frameworks like React, Vue, Svelte, and much more. The more you learn about Vanilla JS, the easier all of the concepts become. 💯

  • @MichaelStephenLau
    @MichaelStephenLau Рік тому

    If the function is only inverting the state of a boolean, does it matter to use prev? i.e. setBooleanState(!booleanState)

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  Рік тому

      Same as count + 1 ..it works - but I recommend always considering previous state. It's a good habit.

    • @MichaelStephenLau
      @MichaelStephenLau Рік тому

      @@DaveGrayTeachesCode Thanks for the clarification. It ensures asynchronous updates occur correctly.

  • @hassanmib6769
    @hassanmib6769 2 роки тому

    which terminal are you using in this video?

  • @umairali2360
    @umairali2360 2 роки тому

    I have a Data from api using redux toolkit and I m getting data on desired page using console. But my state is not updating. I think all code run before updating my state. Please guide

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому

      I can only suggest to follow my examples. I can only guess about what needs changed in your code from here.

  • @Skw384
    @Skw384 2 роки тому

    How do you when you want to update a string?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +1

      const [stringy, setStringy] = useState('initialStringValue')
      And then when you want to change it, use the setStringy() function like this:
      setStringy('newStringValue')
      Please understand the variable name stringy can be anything you want such as name, setName, word, setWord, etc.

    • @Skw384
      @Skw384 2 роки тому

      @@DaveGrayTeachesCode right, thanks a million,
      but do you know if there's such a thing as "prevState" when using string. types as the state?

  • @adventurer2395
    @adventurer2395 2 роки тому

    You say "React updates state in batches." By the that, do you mean React updates state asynchronously?

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому

      Not exactly the same thing. React updates in batches - instead of step by step - to prevent needless component re-renders. More here: blog.saeloun.com/2021/07/22/react-automatic-batching.html

  • @nested9301
    @nested9301 Рік тому

    Hey why u use class instead of className thanks!

  • @behruz_developer
    @behruz_developer Рік тому

    What if you use "+2" instead of "+1"?

  • @lavdev
    @lavdev 3 роки тому

    Hi sir, please help me. i try to send a cookie using postman to server and show cookie in console window but it's show undefined variable, how can i fix that sir

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому

      It is difficult for me to troubleshoot individual problems from afar, but I know you need to manually add the cookie in postman. There is an "Add Cookie" link or button in there.

  • @TheNamesJT
    @TheNamesJT 3 роки тому

    You should make a video where you teach how to deploy a front and back end to Heroku on the same app not separate apps. either use a simple mern app you have already as a way to teach how to do this or even make a whole 2 hour video were we build a simple mern app and then deplay the client and server to heroku. I can't seem to find any information on how to do this online that is current 2021.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  3 роки тому +2

      Great suggestion! ...and it is coming after I finish the backend Node/Express/Mongo series. Combined with the React series, I'll be able to reference the full MERN stack as we build a project. 🚀🚀

  • @FrostDrive
    @FrostDrive 2 роки тому

    I don't understand how just writing prevState makes the program go figure out what the previous value was.

    • @DaveGrayTeachesCode
      @DaveGrayTeachesCode  2 роки тому +1

      It's not a specific word. Instead, it is an anonymous function that receives a default argument value of the previous state. You could call it Dave 😂 but prev or prevState describes it more accurately.

  • @pawanbhatt3847
    @pawanbhatt3847 2 роки тому

    Great is it

  • @ms77grz
    @ms77grz 3 роки тому

    👍👍

  • @stavroskefaleas6320
    @stavroskefaleas6320 3 місяці тому

    Great explanation!