CodexBloom - Programming Q&A Platform

React: Handling Dynamic Form Fields with useForm Hook - Issues with Re-renders and State Loss

👀 Views: 1716 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
react react-hook-form dynamic-forms JavaScript

I'm collaborating on a project where I've been struggling with this for a few days now and could really use some help. I'm working on a form in a React application that uses the `react-hook-form` library (version 7.0.0). I need to create dynamic fields, allowing users to add or remove input fields for their addresses. However, I'm running into an issue where when I remove a field, the entire form seems to be re-rendered, causing the state of previously filled fields to reset. Below is my current implementation: ```javascript import React from 'react'; import { useForm, useFieldArray } from 'react-hook-form'; const AddressForm = () => { const { control, register, handleSubmit } = useForm({ defaultValues: { addresses: [{ street: '', city: '' }] } }); const { fields, append, remove } = useFieldArray({ control, name: 'addresses' }); const onSubmit = data => { console.log(data); }; return ( <form onSubmit={handleSubmit(onSubmit)}> {fields.map((item, index) => ( <div key={item.id}> <input {...register(`addresses.${index}.street`)} placeholder="Street" /> <input {...register(`addresses.${index}.city`)} placeholder="City" /> <button type="button" onClick={() => remove(index)}>Remove</button> </div> ))} <button type="button" onClick={() => append({ street: '', city: '' })}>Add Address</button> <input type="submit" /> </form> ); }; export default AddressForm; ``` When I remove an address field, all other fields seem to be losing their values, and I receive the following warning in the console: "Warning: Each child in a list should have a unique "key" prop." I've ensured that each field has a unique key based on `item.id`, but I suspect the issue may lie in how the form is structured or how state updates are being managed with `useFieldArray`. I've tried using `React.memo` for the individual input components to prevent unnecessary re-renders, but that doesn't seem to work either. Any advice on how to maintain the state of the remaining form fields while dynamically adding and removing fields? I'm using Javascript LTS in this project.