In the React document, it mentions that when rendering a list without keys, React will mutate every child instead of realizing it can keep the items subtrees intact. This inefficiency can be a problem.
I am wondering how I can verify this kind of impact, for example this is the demo I’m writing now:
let renderCount = 0;
function City({ name }) {
console.log('renderCount:', ++renderCount)
return <li>{name}</li>
}
export default function Page() {
const [cities, setCities] = useState(['New York', 'Chicago', 'San Francisco'])
return (
<>
<button onClick={() => setCities(['Beijing', ...cities])}>Add new city</button>
<div>
{cities.map(city => (
<City key={city} name={city} />
))}
</div>
</>
)
}
No matter if I add the key on the city element or not, after I click the button the render count value finally will be 7. Or is there another way like render time to prove the key works?