What are the potential performance implications of using an unstable key (like `Math.random()`) when rendering lists in React?

React JS interview question for Advanced practice.

Answer

It can lead to severe performance degradation because React will destroy and recreate every component in the list on every re-render, losing their state.

Explanation

Using an unstable key like Math.random() is detrimental to performance. Since the key changes on every render, React thinks the old component has been removed and a new one has been added. This forces React to unmount the old component (destroying its state and DOM node) and mount a new one on every single re-render for every single item in the list. This is highly inefficient and leads to loss of component state.

Related Questions