You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Q53 :- What is the output of the following code snippet when the "Click me" button is clicked twice?
function App() {
const [count, setCount] = React.useState(0);
return (
You clicked {count} times
<button onClick={() => setCount(count + 1)}>Click me
);
}
Right Ans : -
Each time the button is clicked:
The event handler runs: setCount(count + 1).
React schedules a re-render with the updated state.
However, the state update is not immediate. The value of count inside the event handler is the value from the last render.
Since count does not update synchronously, clicking twice in quick succession causes both clicks to use the old stale state value.
Step-by-step breakdown:
Click #
Current count
Expression (setCount(count + 1))
Updated count
0 (initial)
0
-
0
1st Click
0
setCount(0 + 1)
1
2nd Click
0 (stale)
setCount(0 + 1)
1 (not 2!)
Thus, after two clicks, count will be 1 instead of 2.
The text was updated successfully, but these errors were encountered:
Q53 :- What is the output of the following code snippet when the "Click me" button is clicked twice?
function App() {
const [count, setCount] = React.useState(0);
return (
You clicked {count} times
<button onClick={() => setCount(count + 1)}>Click me
);
}
Right Ans : -
Each time the button is clicked:
setCount(count + 1)
.count
inside the event handler is the value from the last render.count
does not update synchronously, clicking twice in quick succession causes both clicks to use the old stale state value.Step-by-step breakdown:
setCount(count + 1)
)setCount(0 + 1)
setCount(0 + 1)
Thus, after two clicks,
count
will be 1 instead of 2.The text was updated successfully, but these errors were encountered: