React docs Keeping Components Pure Example

I was going through the React Beta Docs https://beta.reactjs.org/learn/keeping-components-pure and came across this example in which they show what an impure component can be.

Impure Component Example

What I am not able to understand is that in line 5 we are incrementing the guest variable by 1, but why is it incrementing by 2 on every call to the <Cup /> function as it it is getting rendered on the right?

>Solution :

This is explained in the Deep dive lower on the page you linked to. When react is running in Strict Mode, each component is rendered twice when you are in development mode.

The relevant section:

React offers a “Strict Mode” in which it calls each component’s function twice during development. By calling the component functions twice, Strict Mode helps find components that break these rules.

Notice how the original example displayed “Guest #2”, “Guest #4”, and “Guest #6” instead of “Guest #1”, “Guest #2”, and “Guest #3”. The original function was impure, so calling it twice broke it. But the fixed pure version works even if the function is called twice every time. Pure functions only calculate, so calling them twice won’t change anything—just like calling double(2) twice doesn’t change what’s returned, and solving y = 2x twice doesn’t change what y is. Same inputs, same outputs. Always.

If you build the same code to production, you would instead see

<h2>Tea cup for guest #1</h2>
<h2>Tea cup for guest #2</h2>
<h2>Tea cup for guest #3</h2>

Leave a Reply