Тёмный

A cure for React useState hell? 

Steve (Builder.io)
Подписаться 97 тыс.
Просмотров 32 тыс.
50% 1

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

Опубликовано:

 

5 окт 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 70   
@Steve8708
@Steve8708 Год назад
More on useReducer and additional state management tricks and patterns in the full article: www.builder.io/blog/use-reducer
@IceMetalPunk
@IceMetalPunk Год назад
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 Год назад
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 RU-vid 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 Год назад
@@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 Год назад
@@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 Год назад
@@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.
@mnik0128
@mnik0128 Год назад
Finally understood use case for useReducer thank you a lot
@omersoncruz1081
@omersoncruz1081 Год назад
I'm really loving this channel. Thanks for all of your React tips. Keep 'em coming pls
@whitefercho
@whitefercho 9 месяцев назад
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.
@ricko13
@ricko13 Год назад
Love this videos are short and straight to the point! keep it going mate 💪
@MCJini
@MCJini Год назад
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.
@galactusclb5733
@galactusclb5733 Год назад
Can you share a snippet for that hook?
@Palitzonsky
@Palitzonsky Год назад
I would spend lots of money to learn full topic courses from you. Thanks!
@nivaldolemos5280
@nivaldolemos5280 Год назад
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 Год назад
@Nivaldo Lemos Thanks! What I'm trying to say is that I like his approach when he's explaining complex topics.
@Soulis98
@Soulis98 Год назад
You also can use a switch to manage the use reducer better.
@setropleo
@setropleo Год назад
That's pretty cool Steve, but what would be the right way to include typings for the useReducer events and actions?
@pedroalonsoms
@pedroalonsoms Год назад
We can also implement server-side validation for the starDate and endDate calendar stuff. Great video btw
@gamescope2607
@gamescope2607 Год назад
Thank you,your explanation was great and simple to understand
@aryomuhammad8254
@aryomuhammad8254 6 месяцев назад
amazing, thank you!
@benemma5602
@benemma5602 Год назад
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.
@sushi2slushy
@sushi2slushy Год назад
this is really convincing
@yassinesafraoui
@yassinesafraoui Год назад
Straight to the point 👌🙌
@yashnaravade4314
@yashnaravade4314 Год назад
Hey man, love your content! If possible, I would love to see a complete full stack app video from you! 😸
@untlsn
@untlsn Год назад
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
@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}
@taetaebeatz5578
@taetaebeatz5578 10 месяцев назад
Why not add a validation function with useState?
@benoitgrasset
@benoitgrasset Год назад
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.
Год назад
Nice 💯
@DrNabeel20
@DrNabeel20 Год назад
Super cool 🔥
@JEsterCW
@JEsterCW Год назад
Imagine now mixing it with zod, pure power
@CSkyGameGen
@CSkyGameGen Год назад
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
@Sindoku
@Sindoku 10 месяцев назад
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).
@jikaikas
@jikaikas Год назад
why don't I just put the validation when setting the state
@frontend_ko
@frontend_ko Год назад
Okay understood
@Palitzonsky
@Palitzonsky Год назад
Noice! Thank you!
@pb8655
@pb8655 Год назад
How is your Ide so minimal
@valeryp7850
@valeryp7850 10 месяцев назад
All you need is Vue 😌
@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.
@Japhex
@Japhex Год назад
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.
@greendsnow
@greendsnow Год назад
Or better yet, useSvelte :D
@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 Год назад
Sure, if you want your PRs to be rejected, use this reducer...
@AnthonyPaulT
@AnthonyPaulT Год назад
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
@imagineabout4153
@imagineabout4153 Год назад
A cure? How about stop using React?
@sk-sm9sh
@sk-sm9sh Год назад
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 Год назад
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?
@worfrozhenko4032
@worfrozhenko4032 Год назад
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
Далее
Why Signals Are Better Than React Hooks
16:30
Просмотров 479 тыс.
How to share a React Component with the URL
14:11
Просмотров 8 тыс.
Use Maps more and Objects less
5:45
Просмотров 96 тыс.
ALL React Hooks Explained in 12 Minutes
12:21
Просмотров 135 тыс.
Learn React useReducer Hook with Examples
14:19
Просмотров 176 тыс.
Mastering React Context: Do you NEED a state manager?
37:26
UseState: Asynchronous or what?
17:00
Просмотров 66 тыс.
React Hooks: useReducer
12:12
Просмотров 5 тыс.
Interview With A Sr JavaScript Dev | Prime Reacts
24:43