Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the number incremented by 2, instead of my specified 1?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading