About updating state in React #149008
-
Select Topic AreaQuestion BodyWhy does the value of count1 quadruple instead of doubling?
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Question:Why does the value of Answer:The behavior occurs because of nested functional updates and the way React batches state updates for performance optimization. In your
Root Cause:The key issue lies in calling multiple state updates ( Solution:To avoid this behavior, separate the updates in import React, { useState, useEffect } from 'react';
export default function Test3() {
const [count, setCount] = useState(0);
const [count1, setCount1] = useState(1);
const [t, setT] = useState(false);
function handleClick() {
setT(!t);
console.log('t', t);
}
function handleClick2() {
setT(false);
setCount(0);
setCount1(1);
}
useEffect(() => {
if (t && count < 11) {
// Update count
setCount(prev => prev + 1);
// Update count1 separately
setCount1(pr => pr * 2);
}
}, [t, count]);
return (
<div className="flex flex-col items-center">
<h1>Counters that update together</h1>
<div>count: {count}</div>
<div>count1: {count1}</div>
<button onClick={handleClick}>button</button>
<button onClick={handleClick2}>reset</button>
</div>
);
} Hope it helped.💚 |
Beta Was this translation helpful? Give feedback.
Question:
Why does the value of
count1
quadruple instead of doubling? Why issetCount1
executed twice in a row?Answer:
The behavior occurs because of nested functional updates and the way React batches state updates for performance optimization. In your
useEffect
hook,setCount1
is called inside the functional update ofsetCount
. This causessetCount1
to be executed twice during the same render cycle:setCount1(pr => pr * 2)
, which doubles the value ofcount1
.setCount1
to execute a second time. This doubles the value ofcount1
again, resu…