React Hooks useReduce or useState

纵然是瞬间 提交于 2021-02-08 09:23:20

问题


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 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.



来源:https://stackoverflow.com/questions/64942317/react-hooks-usereduce-or-usestate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!