-3

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?

Adriaan
  • 17,741
  • 7
  • 42
  • 75
hatake
  • 1
  • 3
  • If you're using React's strict mode then components render twice in a development build. Is that the case here? – David Aug 14 '23 at 12:51
  • 1
    React may call your component an arbitrary amount of times, in any order. You should not rely on global state - pass `guest` as a parameter. – Coloured Panda Aug 14 '23 at 12:52

1 Answers1

-1

The global state variable might not be a viable approach to achieve this.

As far you have mentioned problem in your question you can try passing param as a count

const  Cup  = ({guestCount}) => {
    return <h2>Tea cup for guest #{guestCount}</h2>;
}

export default function TeaSet() {
  return (
    <>
    <Cup guestCount={1} />
    <Cup guestCount={2}/>
    <Cup guestCount={3}/>
    </>
  );
}

Coloured Panda
  • 3,293
  • 3
  • 20
  • 30
Ram Chander
  • 1,088
  • 2
  • 18
  • 36