skip to Main Content
let guest = 0;

function Cup({name}) {
  guest = guest + 1;
  console.log(name,guest);
  return <h2>Tea cup for guest #{guest}</h2>;
}
return (
<>
        <Cup name={"one"}/>
        <Cup name={"two"}/>
        <Cup name={"three"}/>
</>
)

Output : Output | Console Output

The guest variable is not a state and changing it will not cause a re-render right. ?
I know i should use a state but i want to know how this code executes and why

2

Answers


  1. Chosen as BEST ANSWER

    This was given by chatGPT but i do not know it is the real reason

    React may call function components multiple times whenever it needs to construct the virtual DOM for comparison with the actual DOM. This is part of React’s reconciliation process, which is used to determine what changes need to be made to the actual DOM to reflect the current state of the component tree.
    
    In your case, each Cup component increments the guest variable by 1 every time it’s called. However, due to React’s reconciliation process, the Cup components are likely being called more times than you expect, leading to a higher final value for guest.
    

  2. You are using same component in render but its three different component to render,so the guest variable will have its 3 instances.

    1 component 1 variable.

    So,if i am not wrong 3 component 3 variable are there.
    its working as it is supposed to.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search