skip to Main Content

So, I am learning react.js and was looking at the documentation where they have given a code for impure component

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 />
    </>
  );
}

and this is the output of the above code:

output

I don’t understand why this is the output. After adding seeing the log output I saw that the Cup component is running twice. So, my questions are:

  1. Why does this Cup component run twice?
  2. Even if it runs twice, why does it not print the other numbers (1, 3 and 5)?
  3. Also when I print the guest variable in the TeaSet component it says that guest is 0 no matter where I print it, why is this?

2

Answers


  1. Nice to hear that you’re learning React. AS your Queries let me clear a few basic funda i.e.

    => React runs with 2 virtual Doms and due to that the function will be called Twice. For that either you may disable "Strict Mode" from index.js.

    But that is not a better way, So instead of that you may use UseEffect Hook.

    function Cup() {
      let [guest,setGuest] = useState(0);
    
      useEffect(()=>{
      setGuest(guest + 1);
      ,[])
      return <h2>Tea cup for guest #{guest}</h2>;
    }
    

    For the Detailed information about UseEffect Hook Click Here

    I hope your queries wil be solved using this, All the Best.

    And As you’re expecting to render in TeaPost Component, It can’t be rendered with different values by the mentioned snippeas Changes will be applied Globally.

    Login or Signup to reply.
    1. React runs in a strict mode if you use the <StrictMode/> component to help you find accidentally impure code.

    Strict Mode always calls your rendering function twice

    1. React update the DOM in "commit phrase", not "render phrase"

    2. The order of the render phrase in the React component tree is: parent => child. It means the render function of the parent component TeaSet will be called first(at this time the value of guest variable is 0), then the child component Cup.

    See https://stackoverflow.com/a/76218354/6463558 and Fixing bugs found by double rendering in development

    The

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