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:
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:
- Why does this
Cup
component run twice? - Even if it runs twice, why does it not print the other numbers (1, 3 and 5)?
- Also when I print the
guest
variable in theTeaSet
component it says thatguest
is 0 no matter where I print it, why is this?
2
Answers
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.
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.
<StrictMode/>
component to help you find accidentally impure code.React update the DOM in "commit phrase", not "render phrase"
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 ofguest
variable is0
), then the child componentCup
.See https://stackoverflow.com/a/76218354/6463558 and Fixing bugs found by double rendering in development
The