Robert
Robert

Reputation: 564

React Hooks useReduce or useState

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:

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?

Upvotes: 1

Views: 1440

Answers (1)

lifeisfoo
lifeisfoo

Reputation: 16294

From the useReducer documentation:

useReducer is usually preferable to useState 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.

Upvotes: 3

Related Questions