Issue
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?
Solution
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.
Answered By - LMichiels
Answer Checked By - - David Marino (ReactFix Volunteer)