I have the following code in React:
let guest = 0;
function Cup() {
guest = guest + 1;
return <h2>Tea cup for guest #{guest}</h2>;
}
export default function TeaSet() {
return (
<>
<Cup />
<Cup />
<Cup />
</>
);
}
I expected the result to be:
Tea cup for guest #1
Tea cup for guest #2
Tea cup for guest #3
However, the following is returned:
Tea cup for guest #2,
Tea cup for guest #4,
Tea cup for guest #6
Why is guest
incremented by 2, instead of the 1 I specified?
>Solution :
This is because of Strict Mode
Your components will re-render an extra time to find bugs caused by impure rendering.
I you disable it i.e. remove <React.StrictMode>...</React.StrictMode>
wrapper in your index.js file, you will see the expected output, but you do that just to see the real reason, it is recommanded to use strict mode in dev