React queuing state updates inside useEffect with strict mode

this isn't really practical but I have this code
function App() {
const [count, setCount] = useState(0);

useEffect(() => {
setCount((prev) => prev + 1);
setCount((prev) => prev + 1);
}, [ ])

return (
<p>count is {count}</p>
)
}
function App() {
const [count, setCount] = useState(0);

useEffect(() => {
setCount((prev) => prev + 1);
setCount((prev) => prev + 1);
}, [ ])

return (
<p>count is {count}</p>
)
}
when this runs with strict mode enabled it renders count is 4. The strict mode runs the useEffect twice but because we are using updater function format for state it will pass the latest state value. so we are getting 4 instead of 2. my question is does this mean using updater function in useEffect is bad? I have not had a need to use updater functions so I am not sure if this is how it should be.
1 Reply
Ganesh
GaneshOP2mo ago
this works fine if you use it in an event handler since strict mode doesn't affect them

Did you find this page helpful?