Why key prop is not required when a component is used twice?

Viewed 30

I thought I understood the role of key prop in react but then I couldn't figure why using the same component repeatedly does not require key prop such as in the following example.

Say I have a Like component that looks like this:

function Like() {
    const [c, setC] = useState(0);

    return (
        <div>
            <h3>Liked: {c} times</h3>
            <button onClick={() => setC(c+1)}>Like!</button>
        </div>
    );
}

And in the App component, I have

<div>
  <Like />
  <Like />
</div>

React doesn't seem to be bothered by the fact that there are two identical components. The count is updated correctly whenever the Like! button is pressed.

0 Answers
Related