'Understanding React's Key Property Outside Of Arrays

I encountered this behaviour in React and don't understand what is going on exactly. Say I have two select elements, the first is controlled by React, and the options of the second are controlled by the first, like this:

export default function App() {
  const [i, setI] = useState(0);
  return (
    <form>
      <select value={i} onChange={(e) => setI(parseInt(e.target.value, 10))}>
        {[0, 1, 2, 3].map((i) => (
          <option value={i} key={i}>
            {i}
          </option>
        ))}
      </select>
      <select>
        {[0, 1, 2, 3].map((j) => (
          <option value={i + j} key={i + j}>
            {i + j}
          </option>
        ))}
      </select>
    </form>
  );
}

So there are intersections between the option sets for the various states, but I want the second select element to always reset itself after the state changes. To make this work, I put a key property on it, like <select key={i}>. This makes it work again, but I don't know what the key property exactly does outside of an array, all the documentation I found refers to arrays. My intuition was that it somehow makes changes to the DOM when the key property changes. But now to the part that confuses me even more. In my current application I have a construct similar to this:

export default function App() {
  const [i, setI] = useState(0);
  const [options, setOptions] = useState([0, 1, 2, 3]);
  useEffect(() => {
    setOptions([i, i + 1, i + 2, i + 3]);
  }, [i]);
  //like before
  <select key={i}>
    {options.map((j) => (
      <option value={j} key={j}>
        {j}
      </option>
    ))}
  </select>
  //like before
}

To me it looks like it should evoke the exact same behaviour as before. Yet the selection element stops resetting again. Now I can get it back to work by putting <select key={options}> instead of <select key={i}>. Yet I have really no idea why any of this works the way it works, or if it will keep working the way it currently works.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source