Top 6 React Hook Mistakes Beginners Make

SdĂ­let
VloĆŸit
  • čas pƙidĂĄn 7. 06. 2024
  • FREE React Hooks Simplified Course: courses.webdevsimplified.com/...
    📚 Materials/References:
    FREE React Hooks Simplified Course: courses.webdevsimplified.com/...
    Reference vs Value Video: ‱ Reference Vs Value In ...
    Reference vs Value Article: blog.webdevsimplified.com/202...
    🌎 Find Me Here:
    My Blog: blog.webdevsimplified.com
    My Courses: courses.webdevsimplified.com
    Patreon: / webdevsimplified
    Twitter: / devsimplified
    Discord: / discord
    GitHub: github.com/WebDevSimplified
    CodePen: codepen.io/WebDevSimplified
    ⏱ Timestamps:
    00:00 - Introduction
    00:39 - Using state when you don’t need it
    02:57 - Not using the function version of useState
    06:44 - State does not update immediately
    08:25 - Unnecessary useEffects
    12:40 - Referential equality mistakes
    16:55 - Not aborting fetch requests
    #WebDevelopment #WDS #JavaScript

Komentáƙe • 482

  • @IceMetalPunk
    @IceMetalPunk Pƙed rokem +498

    React's own docs explicitly recommend using state-controlled inputs over refs whenever possible. It refers to the ref method as "quick and dirty" because it lets the DOM handle tracking the value instead of React, which can sometimes cause unexpected behavior when React renders its virtual DOM. So... yeah. I think for forms, especially large ones, it's better to keep track of values in a single state object with key-value pairs. That does mean it'll re-render whenever a value changes, but since React only manipulates the DOM for the one input that's changed, it's not a big deal; and it allows React to have more control over, and more understanding of, the inputs, for optimizations.
    The main issue with using local variables instead of useEffect for composite values is future-proofing: when you add more state to the component, those variables will be re-evaluated on every re-render even if they don't need to be. In such cases, I think useMemo is the optimal solution; in fact, it's why useMemo exists! (And I believe recomputing a memoized variable doesn't trigger a re-render the way setting state does, though I couldn't find anything definitive about that.) But you are right that in some cases, you don't need to listen for changes at all, since you can just use the new value at the same time as you're setting it on the state.

    • @SahraClayton
      @SahraClayton Pƙed rokem +29

      I think useRef should be used for forms, you don't want component re-rendering on every key stroke just for a form, but if you was using a search/filter input where you are filtering on the users key stroke then you would need to useState and make it a controlled component.

    • @chonmon
      @chonmon Pƙed rokem +5

      @@SahraClayton It only re-rendered the input DOM tho? Instead of the whole form if I understand it correctly. I don't think it's a big deal.

    • @ccrsxx
      @ccrsxx Pƙed rokem +23

      @@chonmon yes, not to mention you'll always want to have some kinda validation on the form.

    • @SahraClayton
      @SahraClayton Pƙed rokem +4

      @@chonmon it's not a big deal but if you can avoid any components from rerendering no matter how small is just a bonus. Also it's less syntax in that component, which looks nicer

    • @thienhuynh7962
      @thienhuynh7962 Pƙed rokem +7

      @@SahraClayton then you can opt for other event like submit or blur to minimize re-render. Although useRef is a fine solution since there’s no re-render, using it with forms that have many fields or require validation will give you a hard time managing these fields’ value and their behaviors

  • @runonce
    @runonce Pƙed rokem +52

    For handling form why not simply grab the input values from the onSubmit event? No need for state or refs.

    • @twothreeoneoneseventwoonefour5
      @twothreeoneoneseventwoonefour5 Pƙed rokem +22

      Yes that is what I usually do.
      const formData = new FormData(e.currentTarget)
      and then
      const [username, password] = [formData.get("username").toString(), formData.get("password").toString()];
      looks cleaner to me than using refs or state there
      well I still use state for input validation though

  • @jackwin9641
    @jackwin9641 Pƙed rokem +1

    well this is what I am looking for ages. THANKS KYLE, you made my day, now I can revise my old code at a higher level

  • @jennifermagpantay7933
    @jennifermagpantay7933 Pƙed rokem +4

    Golden tips! Love content like that with different case scenarios and clear explanation! I have learnt so much! Thanks for sharing!

  • @asmmisfar
    @asmmisfar Pƙed rokem +2

    Hey Kyle,
    This is really very helpful for me.
    Tomorrow I have a task to complete in my office.
    I was worried about how to do that.
    but, this video gave me a clear idea about that.
    Thanks a lot. Keep going, bro.
    Loves from Sri Lanka ❀

  • @bowenp01
    @bowenp01 Pƙed rokem +15

    Fantastic! I’m just learning react and you’ve explained the funky behaviour I’ve been getting with useState perfectly. Thanks for taking the time to make these videos 😊

    • @rubyvi7308
      @rubyvi7308 Pƙed rokem

      Why are you excited to watch while the other crying are u happy

  • @Toomda
    @Toomda Pƙed rokem

    This was soo helpful. I had a beginner project, just for fun and I almost made all of the mistakes. I just fixed my code, and it looks much better now. Thank you

  • @deadlock107
    @deadlock107 Pƙed rokem +2

    It was worth to watch, I learned pretty valuable things especially the fetch abort, it's golden, thank you!

  • @nsontung
    @nsontung Pƙed rokem

    one of the best React tips I ever learn on CZcams. Thank you so much

  • @belkocik
    @belkocik Pƙed rokem +1

    amazing video for react beginners. :) Thank you. Looking forward for more react mistakes that beginners and more advanced devs make

  • @paulbird2772
    @paulbird2772 Pƙed rokem +9

    Very clear video, I just switched to Typescript for last major project, took a bit of effort initially but rewards are great, the build step catches a good few errors very early. I think not using TS could be added to your list. I expect many that haven't given it sufficient time will disagree.

    • @dannyj7262
      @dannyj7262 Pƙed rokem +3

      I spent hours on my degree final project sorting out errors that js didn't pick up until I tried to run a piece of code with an error in. Switched to TS and it's a million times better and Id also say I've learnt a lot more too

  • @WorkThrowaway
    @WorkThrowaway Pƙed měsĂ­cem

    This was a great video and helped me solve an issue i had with my hook, namely having multiple states update with an action needed once they were both updated. it took a while to wrap my brain around it, but this video really helped give me the vision. love your videos and that you go super in depth (in the longer ones). probably the best coding tutorials on youtube. if i ever get my web dev dream job, i will be getting you a few coffees/beers.

  • @michalbilinski4168
    @michalbilinski4168 Pƙed rokem

    Hands down, what a perfect rhetoric - watched it with great pleasure - thanks

  • @adnanhaider9302
    @adnanhaider9302 Pƙed rokem +9

    The number of useEffect gotchas and permutations are just never ending. I have such a love hate relationship with this hook.

  • @kuken72
    @kuken72 Pƙed rokem

    This was really straight to the point and very helpful. Thank you Kyle! :)

  • @CarlosRenanFonsecadaRocha
    @CarlosRenanFonsecadaRocha Pƙed rokem +9

    A good thing to point out about the first mistake is that a good UX informs the user if the field has any errors while they are typing; in this case, this is not possible. Better to stick with states, but it is a nice thing to know.

  • @vaibhavsri.
    @vaibhavsri. Pƙed rokem

    Really useful one. Please keep on making great informative videos like this. You're the best!

  • @kamelnazar-instructionalde9740

    This worked incredibly well! I can finally play it thanks

  • @mikeonthebox
    @mikeonthebox Pƙed rokem +11

    I'm thankful I found Svelte and don't have to deal with this complexity. Svelte makes everything so much intuitive. Like yes, there are still some special cases and implementations where you require some special syntax, but for the most part it's just writing regular JS without having to think what wrapper you need.

  • @saheedsimisaye8978
    @saheedsimisaye8978 Pƙed rokem +3

    Most valuable React tips I have learnt regarding some bad code practices I have been applying in React. Thanks for this very comprehensive video with lots of valuable information covered in just over 20mins.

  • @DarkFlarePrince
    @DarkFlarePrince Pƙed rokem

    This is the single most useful video I've seen since I started React coding

  • @Caspitein
    @Caspitein Pƙed rokem +46

    Interesting video Kyle! I noticed I do make a few of these mistakes myself. I think the problem is that us developers can be a bit "lazy" learning new frameworks. I understand how the useState and useEffect hooks work and I never took the time to learn about useRef and useMemo for example.

    • @coderyan
      @coderyan Pƙed rokem +4

      totally!

    • @Spyrie
      @Spyrie Pƙed rokem

      You'll use it once you handle big data and use expensive functions that can block the main thread

    • @d.ilnicki
      @d.ilnicki Pƙed 11 měsĂ­ci

      Well I this case the "lazy" one is the video author. Recommending using refs over state on 1.34M subscribers is a crime.

  • @pedrocruz8164
    @pedrocruz8164 Pƙed rokem

    some of the senior developers in a company I worked for used to not approve my PRs asking for me to not use useRef to the store any state in react component. It is nice to see someone explaining why not every state needs to be rerendering the component on every data update.

  • @taulantus
    @taulantus Pƙed rokem +4

    For the first case you don’t need state or refs the onSubmit function has access to all the input fields via the event parameter

  • @workwithwegs4541
    @workwithwegs4541 Pƙed rokem +3

    Hey Kyle! Thanks a lot for your awesome videos! Have you tackled about using normal function and arrow function in react js? You seem to use both but I'm not sure what your criteria is. Hope you make a video about it! Thanks!!

  • @darkmift
    @darkmift Pƙed rokem +1

    Excellent explanation on state setter usage

  • @Infinizhen
    @Infinizhen Pƙed rokem +1

    Great video. I don't know what more can i say. Cheers!

  • @ori-kapkap
    @ori-kapkap Pƙed rokem

    It's very helpful for React beginner like me! Thank you for your videos :)

  • @mikejuli8243
    @mikejuli8243 Pƙed rokem

    Man, using setCount( (count)=>{count + 1} ), it's the greatest way how to handle this real react problem! That's was extremely beneficial for me !!!!! Thank you!

  •  Pƙed rokem

    You just prevented some lay offs, great job.

  • @developer_hadi
    @developer_hadi Pƙed rokem +1

    Thank you so much, as a beginner you helped me a lot

  • @nigeryanes1987
    @nigeryanes1987 Pƙed rokem +1

    Excellent video, thank you very much.😊

  • @loicrutabana1884
    @loicrutabana1884 Pƙed rokem

    Amazing! You make great content. I especially like your youtube shorts

  • @louis-emmanuelisnardon8308

    Great video ! Well explained ! Thank you, I'm modifying my code right now...

  • @wisdomelue
    @wisdomelue Pƙed rokem +1

    best explanation of useMemo out heređŸ‘đŸœ

  • @User36282
    @User36282 Pƙed rokem +3

    You really have a talent for education my man. Whenever I'm not understanding something in web dev now I just search for web dev simplified and boom there's always a video on it. Thank you! These were really good tips for those of us just getting into front end :)

  • @mehmetacikgoz9814
    @mehmetacikgoz9814 Pƙed rokem +332

    Using refs instead of state does not seem right in this scenario. First of all, such a render does not create any overhead since behind the scenes react will do equivalent of what you have done with refs. Besides, these code will probably be improved with validators etc. which will result going back to state version

    • @rvft
      @rvft Pƙed rokem

      Sus lan

    • @neutralface
      @neutralface Pƙed rokem +57

      You're correct. React has always preferred controlled components (react handles input value) over uncontrolled components (DOM handles input value). This is second time I see Kyle making this counter-argument to use refs, which I think is incorrect.

    • @ACMonemanband
      @ACMonemanband Pƙed rokem +9

      This is really debatable, as the scenario Kyle mentioned is that, all the inputs are only used upon form submission. For experienced React developers, we have always been using controlled components and get really used to it, so we are very unlikely to use Kyle's uncontrolled ways in any circumstance.

    • @neutralface
      @neutralface Pƙed rokem +18

      @@ACMonemanband True. Refs are mentioned in the "Escape hatches" section in the new react docs, which for me intuitively tells that refs are used as secondary option when first option of controlled components doesn't work.

    • @rand0mtv660
      @rand0mtv660 Pƙed rokem +19

      ​@@ACMonemanband These days I usually just use react-hook-form and don't worry if something is controlled or uncontrolled in a most forms. The fact is that for more complex forms that might compute a lot of stuff, uncontrolled form inputs are better because they won't re-render the whole form on each input change. If you need to do any active validation, you'll probably have to go for controlled forms because you'll have to react to form changes all the time and not just on submit, but in cases where you just need to validate on submit, you probably want to go for uncontrolled inputs.
      Only reason I dislike his input ref example is because you'll rarely only work with two field forms in the real world and you'll most likely have multiple (more complex) forms in your app. At that point, just reach for something like react-hook-form and never worry about building forms in React.

  • @mariumbegum7325
    @mariumbegum7325 Pƙed rokem

    Really good video, very informative and explaining in a clear way.

  • @marwenlabidi_dev
    @marwenlabidi_dev Pƙed rokem +2

    thank you for this great quality content

  • @noelfrancisco5778
    @noelfrancisco5778 Pƙed rokem

    great tutorial, I learned something new today. Thanks :)

  • @ethanmcrae
    @ethanmcrae Pƙed rokem +1

    I really appreciate this video!! 🙌

  • @movsesaghabekyan9794
    @movsesaghabekyan9794 Pƙed rokem +1

    It was amazing man. Thanks a lotđŸ”„đŸ”„

  • @habibiSD
    @habibiSD Pƙed rokem

    Well done sir, excellent video. Thank you for your hard work.

  • @shivshankarshejwal6728
    @shivshankarshejwal6728 Pƙed rokem +2

    Nice tip last one.Thanks

  • @joseff5998
    @joseff5998 Pƙed rokem

    I really appreciate your explanations. Top-notch!.

  • @MaherOmri
    @MaherOmri Pƙed rokem

    Amazing explanation! Many thanks

  • @maximpolsky2683
    @maximpolsky2683 Pƙed rokem

    Many thanks! Good luck with your channel! Greetings from Kyiv!))

  • @charlesvicencio2461
    @charlesvicencio2461 Pƙed rokem

    Thank you Kyle!

  • @evrentank6402
    @evrentank6402 Pƙed rokem

    Thanks a lot. These are very important and useful knowledges.

  • @mingxindong3150
    @mingxindong3150 Pƙed rokem

    that just makes so much sense!!!! thank you for bring the good code

  • @vorkosiganhs
    @vorkosiganhs Pƙed 7 měsĂ­ci

    Amazing video, thx a lot!

  • @beinghappy3924
    @beinghappy3924 Pƙed 11 měsĂ­ci

    You really deserve thumbs up from me. Good Job. 👍

  • @igorkushnir4966
    @igorkushnir4966 Pƙed rokem

    last one just perfect! thanks!

  • @yashpreetbathla4653
    @yashpreetbathla4653 Pƙed rokem +1

    Great video dude thanks :)

  • @crim-son
    @crim-son Pƙed rokem +1

    This is really helpful ❀

  • @it9hektar
    @it9hektar Pƙed rokem

    good explanation !!!, my problem can be solved, thank you very much..

  • @appuser
    @appuser Pƙed rokem

    This video rocked my world. Had quite a REACTion to it.

  • @MJstart
    @MJstart Pƙed 11 měsĂ­ci

    Thanks for video Kyle

  • @mangman
    @mangman Pƙed rokem +4

    Great video! useRef seems neat, but you do lose the ability to have real time validation, as that logic would be placed in the onSubmit function.

  • @carlosricardoziegler2650

    Good tips , thanks for sharing

  • @sergiogusto
    @sergiogusto Pƙed rokem

    00:45 tag stores fields value

  • @adtc
    @adtc Pƙed rokem +11

    Good video. One tip: if the arrow function will return an object, you can just put the object inside parentheses instead of using a full code block with a return keyword. Example: () => ({ age, name })
    Also I believe you can simply return controller.abort instead of returning an anonymous function which calls controller.abort()

    • @billynitrus
      @billynitrus Pƙed rokem

      Would you be able to explain to me what is being passed to currentCount at around 6:00? Does calling setState automatically pass in the current state as an argument? Not sure how else it would be possible since the parameter name seems to be arbitrary, ie prevState. It sounds like you know your stuff, any help would be appreciated!

    • @zakariaibrahim3750
      @zakariaibrahim3750 Pƙed rokem

      @@billynitrus setState accepts a function which its parameter (currentCount) is the value of ‘count’ before being updated.
      Ex. If count is 9 and you clicked on the ‘+’ button ,if you try to log ‘currentCount’ you would get 9 ,thus ‘return currentCount (9) + amount(1)’ will result in updating ‘count’ to 10

  • @gilsonconceicao5201
    @gilsonconceicao5201 Pƙed rokem

    Thanks. I didn't knew these.

  • @mengfandy7365
    @mengfandy7365 Pƙed rokem +1

    i love react and i love this youtube channel, hi from indonesia

  • @KathidFX
    @KathidFX Pƙed rokem

    It does work as the same as before in case of email and password, but we use usestate , value and onchange to create Controlled components. Uncontrolled components with refs are fine if your form is incredibly simple regarding UI feedback. However, controlled input fields are the way to go if you need more features in your forms.

  • @mystic7207
    @mystic7207 Pƙed rokem

    Awesome explanation ❀

  • @jeromealtariba7339
    @jeromealtariba7339 Pƙed rokem

    excellent ! Big thanks

  • @singhsankar
    @singhsankar Pƙed rokem

    very simple and very useful!

  • @raziechavoshi5994
    @raziechavoshi5994 Pƙed rokem

    super informative and helpful

  • @sagarmishra6746
    @sagarmishra6746 Pƙed rokem

    I even express with words how much this video has helped me. I got answers to lot of my questions. Thanks KyleđŸ’„

  • @ode2877
    @ode2877 Pƙed rokem

    Usefull for beginner like me, thanks 🎉

  • @FSRezende
    @FSRezende Pƙed rokem

    Great! Thanks from Brasil!!!

  • @MrQVeeBoo
    @MrQVeeBoo Pƙed rokem

    Very good, on point, thx

  • @tomasburian6550
    @tomasburian6550 Pƙed rokem

    You are my hero.
    Btw, I think that we all learned the hard way that adding the useState count twice in a row would still do it just once :P

  • @youssefhossam9077
    @youssefhossam9077 Pƙed rokem

    that was helpful thank you

  • @mr.gandalfgrey2428
    @mr.gandalfgrey2428 Pƙed rokem

    Soo good to see that there's finally more than just a guitar in your room :D just kidding, awesome video as always!

  • @hazemalabiad
    @hazemalabiad Pƙed rokem

    You are AMAZING ... Kyle 💐

  • @NathanBudd
    @NathanBudd Pƙed 9 měsĂ­ci +1

    That last useFetch insight is very helpful! I think it could be even more so if combined with some king of debounce? So the fetch only runs after say 0.5s?

  • @jesuscabrita5815
    @jesuscabrita5815 Pƙed rokem

    that useMemo trick... was lovely

  • @user-cp4wf4xy1g
    @user-cp4wf4xy1g Pƙed rokem

    Simple and brilliant

  • @joemathan6101
    @joemathan6101 Pƙed rokem +1

    You would still control re-renders by using denounce on top of state. So, there won't be a need for ref in this case. As the react doc itself suggests us to go with controlled components over uncontrolled components
    Useful video thank you

  • @eiatot6455
    @eiatot6455 Pƙed rokem +2

    {} === {} false is the correct result for more than one reason but what I want to stress is that {} is NOT an object, it is the LITERAL CONSTRUCTOR hense don't tide the symbols to what they actually are, the constructors return objects.
    Excellent video ty.

  • @chanhaoen62
    @chanhaoen62 Pƙed rokem +1

    Thanks for all the react tips! Really helped me a lot :) will you ever put out a video of you playing guitar? haha

    • @lukas.webdev
      @lukas.webdev Pƙed rokem

      I'm pretty sure, that there is already a part in one of his videos, where he plays a solo... But I can't remember how it was called... 😄

  • @komalmadamwar710
    @komalmadamwar710 Pƙed rokem +1

    this is super helpful

  • @nirmesh44
    @nirmesh44 Pƙed rokem

    best tips ever. i also was not using functional way of setting state

  • @ozkanylmaz8046
    @ozkanylmaz8046 Pƙed rokem

    Thank youuuu very much

  • @elmalleable
    @elmalleable Pƙed rokem +3

    if its a simple form then you can just take the values from the form event when you submit and you dont really need to keep state provided you have a vary basic use case for the form, complex validations and connected models then you'll probably go back to using state

  • @sandhilt
    @sandhilt Pƙed rokem

    Thank you for share.

  • @mustaphasalehipourenglish7387

    was great like always

  • @sheriffawzy2998
    @sheriffawzy2998 Pƙed rokem

    Good work Kyle 😉

  • @sam-u-el
    @sam-u-el Pƙed rokem +1

    thank you sir what was informative

  • @g_sami__newn8728
    @g_sami__newn8728 Pƙed rokem

    Useful video❀

  • @anhqui19822011
    @anhqui19822011 Pƙed 2 měsĂ­ci

    Thank you for the great video! Regarding the choice between useRef and useState for form submission, I believe we should use useState instead of useRef. This is because we typically need to reset the input value to empty after submission. For input filtering, updating the state as the keystrokes change is necessary to display the latest value in the UI.

  • @AR7editing
    @AR7editing Pƙed rokem +9

    15:45 in that case instead of useMemo we can directly use in the dependency array person.name and person.age and it will not cause rendering when you change the dark mode checkbox

  • @lilililliilil
    @lilililliilil Pƙed rokem +2

    Great video! I’m glad not making any of those mistakes 😂

  • @monafdaod2133
    @monafdaod2133 Pƙed rokem

    Thanks, A lot👍

  • @AllAboutDev
    @AllAboutDev Pƙed rokem

    Last tip was really important ❀

  • @jessejoseph2643
    @jessejoseph2643 Pƙed rokem

    Thanks Kyle. Funny how I'm an advanced react developer and I make a couple of mistakes you pointed out.

  • @viet.khoaiegg
    @viet.khoaiegg Pƙed rokem

    Learning so much 🎉

  • @sexylittlewilly
    @sexylittlewilly Pƙed 10 měsĂ­ci

    this video is all react people need, thanks a lot.