Modifying a functional component the uses setState hook
dutzi opened this issue · comments
Hey, I have this component:
import React, { useState } from 'react';
const MyComponent = () => {
const [counter, setCounter] = useState(0);
setTimeout(() => {
setCounter(counter + 1);
}, 1000);
return (
<div>
{counter}
</div>
);
};
export default MyComponent;
When I modify setTimeout's body to:
setCounter(counter + 10);
Expected behavior
The counter will now increase by 10 every second.
Actual behavior
The counter increases by 10 every second, but then, a few milliseconds later, in increases by 1 also.
Environment
React Hot Loader version: 4.12.13
-
node -v
: v10.15.1 -
npm -v
: 6.4.1 -
Operating system: macOS 10.14.6
-
Browser and version: Chrome 76.0.3809.132
I went over all open issues and didn’t find anything regarding this. Might be something with my setup.
That should happen only once, as long as there are an "old" effect and a new one. And there is no way to prevent it, unless you wrap setTimeout
with useEffect
, and provide a unmount callback, so the "old" effect could be canceled.