Home > database >  How to make react component with numerous form fields change state in a more efficient way?
How to make react component with numerous form fields change state in a more efficient way?

Time:12-22

I have a component with about 16 input fields. The component itself is quite complex. The problem is that every time it updates the state of the form on input change it triggers a re-render. Rendering that component is a bit expensive, there is a short delay noticeable when you type a character inside an input.

What is best practice in such a case?
Maybe I should update the state only when the user submits the form?

CodePudding user response:

Updating the state on each input change can lead to a lot of unnecessary re-renders, which can impact the performance of your application. One option you could consider is to debounce the input changes so that the state is only updated after a certain amount of time has passed without any further input changes. This can help to reduce the number of re-renders and improve the overall performance of the component.

Another option you could consider is to use a library like React-Final-Form or Formik to manage your form state. These libraries can help to optimize performance by only re-rendering the parts of the form that have actually changed, rather than the entire form on each input change.

It's also a good idea to optimize the rendering of the component itself. You can use the React performance tools to identify any potential performance bottlenecks and optimize them. You can also consider using React.memo or the shouldComponentUpdate lifecycle method to optimize the rendering of the component.

Finally, you could consider updating the state only when the form is submitted, as you mentioned. This would mean that the state is only updated once, rather than on each input change. However, this approach may not be practical if you need to perform any validation or other logic on each input change.

CodePudding user response:

if you don't want to use any other library that manages form state

you can move the form to another component, in this case only the child component that conains your form will be rerendred on changing inputs values, not the parent component, and pass to it the function that handles submit in props to trigger changes in the parent component when you submit the form

  • Related