Home > Back-end >  React docs Keeping Components Pure Example
React docs Keeping Components Pure Example

Time:07-26

I was going through the React Beta Docs 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?

CodePudding user response:

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>

CodePudding user response:

Because with <StrictMode>, the component will render twice, So on each render the guess variable updates, So 2 * 4 will equal to 8.

  • Related