The component is from React’s official documentation’s section Keeping Components Pure.
let guest = 0;
function Cup() {
// Bad: changing a preexisting variable!
guest = guest + 1;
return <h2>Tea cup for guest #{guest}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup />
<Cup />
<Cup />
</>
);
}
When this component is running in strct mode I expected its rendering result to be:
Tea cup for guest #4
Tea cup for guest #5
Tea cup for guest #6
However, the correct result is:
Tea cup for guest #2
Tea cup for guest #4
Tea cup for guest #6
I was confused with the correct result because according to my understanding the rendering happened twice. The steps of each rendering are App -> TeaSet -> 3 Cups. After the first rendering, the value of the guest is 3. So in the second rendering, the first cup shuld be rendered as ‘Tea cup for guest #4’ and so on.
Any help is appreciated!
I have debugged this component. I gave each cup an id and set a break point at the first line of the Cup component. What’s strange is that the break point is met twcie at the first cup in a row!