Fix the React State Bug
HardChallenge 7 of 20
Fix the React State Bug
HardThis React component has a state update issue. The counter doesn't increment correctly when the button is clicked rapidly. Fix the bug.
Challenge 7 of 20
80 XP
Community Solutions
ReactState ManagementHooksJavaScript
Exit ChallengeTest Cases
0/2 passingTest Case #1
Input: Click the button once
Expected: Count: 3
Run tests to see results
Test Case #2
Input: Click the button twice
Expected: Count: 6
Run tests to see results
solution.js
1
<span class="token keyword">import</span> React, { useState } from <span <span class="token keyword">class</span>="token number">039</span>;react<span <span class="token keyword">class</span>="token number">039</span>;;
<span class="token keyword">function</span> Counter() {
<span class="token keyword">const</span> [count, setCount] = useState(<span <span class="token keyword">class</span>="token number">0</span>);
<span class="token keyword">function</span> handleClick() {
setCount(count + <span <span class="token keyword">class</span>="token number">1</span>);
setCount(count + <span <span class="token keyword">class</span>="token number">1</span>);
setCount(count + <span <span class="token keyword">class</span>="token number">1</span>);
}
<span class="token keyword">return</span> (
<div>
<p>Count: {count}</p>
<button onClick={handleClick}>Increment by <span <span class="token keyword">class</span>="token number">3</span></button>
</div>
);
}
<span class="token keyword">export</span> default Counter;Console
Run your code to see output here