React How and why to use keys in React Basic Example


Example

For a class-less React component:

function SomeComponent(props){

    const ITEMS = ['cat', 'dog', 'rat']
    function getItemsList(){
        return ITEMS.map(item => <li key={item}>{item}</i>);
    }
    
    return (
        <ul>
            {getItemsList()}
        </ul>
    );
}

For this example, the above component resolves to:

<ul>
    <li key='cat'>cat</li>
    <li key='dog'>dog</li>
    <li key='rat'>rat</li>
<ul>