A cure for React useState hell?

Поделиться
HTML-код
  • Опубликовано: 12 сен 2024
  • Read more about how you can use useReducer, and other scaleable state management patterns in React, in my latest blog post: www.builder.io...
    #react #javascript #js #webdev

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

  • @Steve8708
    @Steve8708  Год назад +4

    More on useReducer and additional state management tricks and patterns in the full article: www.builder.io/blog/use-reducer

  • @IceMetalPunk
    @IceMetalPunk Год назад +48

    While this makes validation easier, it has a major drawback: this is in essence storing all the state in one object, and recreating that object (via spread) in every update. Which means React can't calculate a minimal render and will have to rerender everything using any part of that state whenever one property is updated.
    It's probably not a big deal for small examples like this, but as your state gets larger and more complex, it's something to definitely keep in mind, especially if you start noticing performance issues with your components.

    • @valascusbracarensis
      @valascusbracarensis Год назад +9

      I was watching it and remembering the meme: "oh no no no no no"... Came right into the comments to see the reactions.
      This is not at all a good practice and I just told RUclips to not recommend me this channel anymore.

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

      React literally won't care for stuff like that jn this case.
      No heavy calculations are being made, its a simple object, why would it affect performance?

    • @IceMetalPunk
      @IceMetalPunk Год назад +4

      @@tariksadiku4723 Rendering to the DOM is relatively costly. And as the component grows, so will its state. The more things React needs to rerender, the more performance hit your app will take. Every render requires React to calculate minimal diffs on its virtual DOM. It's smart enough to only calculate those on state data that has changed, but it's not smart enough to know that a new object with 99% the same data isn't an entirely new set of data.

    • @Lexaire
      @Lexaire Год назад +6

      @@IceMetalPunk It's going to re-render and update the DOM when any of the useState() would have changed anyways, so re-rendering every time event changes is not any more costly. His example is bad for a different reason: he's taken simple useState hooks and made a complicated and mostly useless reducer that is prone to bugs and lumps unrelated logic together. useState is simple.

    • @IceMetalPunk
      @IceMetalPunk Год назад +4

      @@Lexaire The difference is that if you set a single state property, React can do an optimized minimal diff on the virtual DOM because it knows nothing else has changed. By lumping all the state into a single object that gets fully replaced when anything is updated, React no longer knows what's changed and what hasn't, so the virtual DOM diff calculation now has to account for all properties at once every time, which is far more costly.

  • @whitefercho
    @whitefercho 8 месяцев назад

    I started the last year to code and I notice that to avoid the useState hell, I only use this hook once by creating an object and setting properties to it. The convention says too. It is solve passing an updater function argument in the dispatcher: setDispatcher((prevState) => { Body }). Anyway, I'm grateful for watching your vid 'cause now I learned useReducer.

  • @Soulis98
    @Soulis98 Год назад +2

    You also can use a switch to manage the use reducer better.

  • @mnik0128
    @mnik0128 Год назад +2

    Finally understood use case for useReducer thank you a lot

  • @MCJini
    @MCJini Год назад +18

    oh hell no...this is defiantly not the way to do that....
    make a custom hook called useValidation that will accept 2 params, initialValue, validationFunction
    it will return a state and a change function that will validate it.

  • @setropleo
    @setropleo Год назад +8

    That's pretty cool Steve, but what would be the right way to include typings for the useReducer events and actions?

  • @Palitzonsky
    @Palitzonsky Год назад +26

    I would spend lots of money to learn full topic courses from you. Thanks!

    • @nivaldolemos5280
      @nivaldolemos5280 Год назад +4

      The so called "beta" React docs are amazing in this regard. See the useReducer entry, for example. It's has plenty of tips and use cases.

    • @Palitzonsky
      @Palitzonsky Год назад +2

      @Nivaldo Lemos Thanks! What I'm trying to say is that I like his approach when he's explaining complex topics.

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

    Love this videos are short and straight to the point! keep it going mate 💪

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

    We can also implement server-side validation for the starDate and endDate calendar stuff. Great video btw

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

    Know when to use state over reducer and when to use both.
    Key tip: when one state depends on the next one or previous one to execute the use reducer.
    If the state are completely independent from each other and one can work without another then useState.

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

    I'm really loving this channel. Thanks for all of your React tips. Keep 'em coming pls

  • @untlsn
    @untlsn Год назад +8

    I don't like useReducer it's to "redux'y"
    I prefere to write custom hook with validation, or use library with validation like react-hook-form or simply Zod

  • @aryomuhammad8254
    @aryomuhammad8254 6 месяцев назад

    amazing, thank you!

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

    Change in object by { [object_key}: value} is the same how it was going in reducer - but with overheading ACTION_NAME -> convert to -> { [object_key}: value}

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

    Thank you,your explanation was great and simple to understand

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

    Hey man, love your content! If possible, I would love to see a complete full stack app video from you! 😸

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

    Straight to the point 👌🙌

  • @taetaebeatz5578
    @taetaebeatz5578 10 месяцев назад +1

    Why not add a validation function with useState?

  •  Год назад +1

    Nice 💯

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

    Super cool 🔥

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

    interesting, but this works only with javascript, not with typescript, otherwise your object is not strongly typed

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

      What do you mean

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

      You can still do this with Typescript, and thus have it be strongly typed. However as others have mentioned, this isn't actually a particularly good thing to do due to it being pretty inefficient and not particularly reusable. A custom hook which internally uses useState is a much better solution here - you could even make it take in a custom validator function, for instance:
      [{startDate, endDate}, setNewDates, dateErrors] = useValidatedState({startDate: new Date(), endDate: new Date()}, (newStartDate, newEndDate) => newEndDate >= newStartDate)
      This is simple enough to build as a custom hook, is massively powerful, and doesn't cause all the child components to re-render if we only change an attribute that only a couple of the components actually use.

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

    It still doesn't correctly safeguard the endDate, user can still do that without any prevention, all you are doing is interject it and modifying it, rather than disallowing that input altogether.

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

    Imagine now mixing it with zod, pure power

    • @CSkyGameGen
      @CSkyGameGen Год назад +2

      Couldn't you just use zod then without useReducer? Or yup in this case, you're validating some data with both of those libraries. I guess if you don't want to install any libraries you could just use the useReducer

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

    Okay understood

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

    why don't I just put the validation when setting the state

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

    I don’t understand why people don’t use this hook more often. They’d rather just keep piling up on useState calls, and it becomes increasingly complex. Especially if you require a use effect to do something paired with the fact that each use effect should essentially be doing one thing (generally speaking).

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

    Noice! Thank you!

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

    All you need is Vue 😌

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

    How is your Ide so minimal

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

    How to error handle if you fail the validation?

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

      If you go this route, you'd want one of the properties of the object be an array of error messages. You then populate that if you get a validation error, and then the component should check that property and render an appropriate message if it has values in.

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

    Or better yet, useSvelte :D

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

    You had me until the mention of the word redux. I jest, this is great and does make a ton of sense in that very specific use case, but that aside context and useState/useReducer for those centralised rules at a higher level should be sufficient for most things. Going back to redux-esque way of firing actions and using stores feels like a humungous step backwards into much much higher volume, much more complex code.

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

    Yeah no, it's basically rendering everything anything changes, which defeat the purpose of minimal rendering.

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

    Now I know why people are obsessed with Redux 😅

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

    OMG awesome

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

    Sure, if you want your PRs to be rejected, use this reducer...

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

    just create a custom hook that has functions that update each part of the state. useReducer is confusing and it forces people that create terrible state abstractions. Too many noobs in youtube. I should start my own react series

  • @worfrozhenko4032
    @worfrozhenko4032 Год назад +6

    React is so gross, causing brain damange in everyone.

    • @sk-sm9sh
      @sk-sm9sh Год назад

      I've been coding for 15 years. It's the biggest balooney that I've seen. Now to be fair at it's beginning React wasn't that bad. JSX was always terrible but at least least apart from JSX it was still simple straight forward component framework. But all this stuff with hooks... Really only company as defunct as Facebook could invent this nonsense.

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

      You have to have a brain deficiency if you think this is complicated

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

    A cure? How about stop using React?

  • @sk-sm9sh
    @sk-sm9sh Год назад +2

    React is biggest balooney I've seen during my 15 years of coding. Maybe 15 years of coding ain't that long but I also know ppl who say it's biggest balooney in their 30years+ long coding careers.

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

      I’ve seen code from consultants that have written code for 30 years . That doesn’t make them good. Or their opinion especially valuable. They also don’t like typescript and would prefer writing in js without even eslint setup or a functional deploy script. The language they have used for 30 years is typed.

    • @sk-sm9sh
      @sk-sm9sh Год назад

      @@benscherer7256 sorry I never met anyone who coded 30 years and would have anything remotely similar to what you're saying.

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

      So what would be better in your opinion

    • @sk-sm9sh
      @sk-sm9sh Год назад

      ​@@CSkyGameGen really depends on use-case. If you describe what project you want to build, I can describe you preferred architecture, from there we can start looking what tools fit best. There is no silver bullet.

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

      @@sk-sm9sh ok let's say for example a store where you can order products and search for them with categories and everything. Basically your average online store.
      Also if it depends on the use case are you saying that there is no use case for react at all?