Home > Enterprise >  React state management rendering for one object or array of objects
React state management rendering for one object or array of objects

Time:05-14

I'm learning React and starting with handling state in a CRUD form via the useState Hook. Something like this:

const [data, setData] = useState({});

where data is the object containing the state of the form and his props are the values of the inputs.

I have two concerns:

1) Unnecessary rendering. If when an input is changed (onChange or onBlur event) I update the state, via a typical handleChanged function, for example:

const handleChanged = (e) => {
      setData(...data, [e.target.name]: e.target.value)
});

does the form render only the specific changed input or the entire form (all inputs) ? In case it was for all inputs, how could that be avoided?

2) Arrays and useState. If instead of having a single data object I have an array of data objects, eg. in a editable table, how would the useState be handled for each array element? I have searched for examples but they are all for a single object.

CodePudding user response:

Part 1:

As per the following definition: React schedules a render every time the state of a component changes. useState changes only the component where change occurs. In your case, I believe, the re-render occurs.

Why re-invent the wheel when it's already invented?

If you are concerned about forms, you should explore this library: https://react-hook-form.com/

Also, you will be able to properly visualize it in the section Isolate Re-renders of https://react-hook-form.com/

Part 2:

You can use useState to store an Array and that Array can be a set of Objects.

In order to render components from the Array, you can further use map function.

Or if you want to simply access the data, then you can use index values to access objects.

I hope, this makes sense.

Explanation could have been better if the whole code snippet for your concerns was shared.

Regards, Shameel Uddin

  • Related