DEV Community

Discussion on: A cure for React useState hell?

Collapse
 
brense profile image
Rense Bakker

Rerender is ignored for the other 5 fields if their values didnt change, the props will be the same and it will keep the DOM elements that are already there for those fields.

How would you suggest to make a component to edit some data model, like a calendar event, that has multiple fields (e.g. name, date, description, etc.)? It's a pretty common case to have modals like these with multiple input fields and the solution suggested by the author is pretty good imho.

Collapse
 
dikamilo profile image
dikamilo • Edited

EditCalendarEvent components holds global state as single states with useState or as single object with useReducer, so it will re render whole component on each change. With useReducer new object is returned so it have same component update behaviour as using multiple useState. Only one change is here that you have validation logic in one place.

You can create separate components for inputs that will hold own state or use refs instead of state for that data.

A lot of form don't require that anyway, you can just get form data in onSubmit callback like so:

onSubmit={(e) => submitForm(new FormData(e.currentTarget))
Enter fullscreen mode Exit fullscreen mode

useReducer is nice for things that changes together, form independent input fields in form, not so much.

Thread Thread
 
brense profile image
Rense Bakker

I dont think you can consider the event data as global state, its bound to the specific form component. You have to consider the case here that you are fetching the event data from a database (when editing for example). You are not going to do individual database queries for each field, so you need some way to pass down the event data to the individual input components.

There is no issue with this aslong as you keep the values referentially equal, so React is able to determine that the props/state for the other inputs didnt actually change. If React can determine that the props/state did not change, it will not make any DOM changes for those components.

The example by the author with the useReducer hook, is a good/clean way to achieve this.

Thread Thread
 
dikamilo profile image
dikamilo

I dont think you can consider the event data as global state, its bound to the specific form component.

Yes, I mean "global data" in context of this specific components tree.