问题
I have a form with 30 fields and all those fields are a template from a value in a dropdown, if I change the value of the template I will end up creating a custom template.
So the action is:
- When we are changing a value from the form, the template will change in custom template
As you can see there are some logic that come up and down and I'm worried about the multiple setState declaration and call. Should I use useReducer
or useState
?
回答1:
From the useReducer documentation:
useReducer
is usually preferable touseState
when you have complex state logic that involves multiple sub-values or when the next state depends on the previous one.
You should use the useReducer to manage you complex form, otherwise you'll end up having many useState
and a many useEffects
to update every other state when one of those useState
changes. In this case useReducer
is definetevely the best option.
In this way all your UI elements will be a visual representation of the useReducer
state, so any value change in a field must trigger an action to update the state and then the UI.
You can also try using an existing library like react-hook-form, but this choise is up to you and depends on your requirements.
来源:https://stackoverflow.com/questions/64942317/react-hooks-usereduce-or-usestate