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:
Cup
component run twice?guest
variable in the TeaSet
component it says that guest
is 0 no matter where I print it, why is this?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.