score:1

Accepted answer

keys are used for lists to help react identify which items have changed, been added or been removed. in your case you're using the name as the key, so whenever you update the value of your input field, the key is updated as well. react detects this as an element being removed, and a new element being added.

so instead of just updating the value, react actually removes the input field, and add an input field again, which is why the input loses focus after updating one of the inputs.

score:2

when you are mapping through names which is an array of input values. you are rendering the inputs in the following way.

return (
  <div>
    {/***** the key is wrong!!! */}
    {names.map((n, i) => (
      <input key={n} value={n} onchange={(e) => setname(i, e.target.value)} />
    ))}
  </div>
);

as soon as you change the input, setnames is triggered through your setname via onchange.

this means react will now check for new items generated.

since key={n} would change the input itself i.e a new input element is generated and updated now in the dom, that is why you lose focus each time when you change it.

this is not the case, when you are using index as the key. because then the keys of input remain same and only the value changes.

however, there are some caveats using index as keys too.

you can read more about them here:

  1. https://reactjs.org/docs/lists-and-keys.html
  2. https://reactjs.org/docs/reconciliation.html#recursing-on-children

Related Query

More Query from same tag