React Hook Form: How to Dynamically Add Fields That Retain State Without Unnecessary Re-renders
I'm relatively new to this, so bear with me. I've looked through the documentation and I'm still confused about I'm working with React Hook Form (version 7.x) and trying to implement a dynamic form where users can add multiple fields of the same type (e.g., a list of emails). However, I'm facing an issue where added fields lose their state when the component re-renders, which seems to happen every time the form is submitted or when the parent component updates. I've already tried using `useFieldArray` from React Hook Form, but it feels like the whole form resets upon adding new fields. Hereβs a simplified version of my form: ```jsx import React from 'react'; import { useForm, useFieldArray } from 'react-hook-form'; const DynamicEmailForm = () => { const { register, control, handleSubmit } = useForm({ defaultValues: { emails: [''] }, }); const { fields, append, remove } = useFieldArray({ control, name: 'emails', }); const onSubmit = (data) => { console.log('Form data:', data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {fields.map((item, index) => ( <div key={item.id}> <input {...register(`emails.${index}`)} defaultValue={item.email} // Important to set default values /> <button type="button" onClick={() => remove(index)}>Remove</button> </div> ))} <button type="button" onClick={() => append('')} > Add Email </button> <input type="submit" /> </form> ); }; export default DynamicEmailForm; ``` The main issue seems to be that the `defaultValue` prop is not being maintained properly for dynamically added inputs. Iβve also checked the console and noticed that the inputs are re-rendering, but their values are not retained, leading to the form not having the expected output when submitted. I tried wrapping the `append` and `remove` functions with `React.memo` for optimization, but it did not help. Is there a recommended way to manage this in React Hook Form while ensuring that input state is preserved? Any advice would be greatly appreciated! I'm working on a API that needs to handle this. Am I missing something obvious? My development environment is Ubuntu. Am I missing something obvious?