Closed as not planned
Description
React version: 19
Steps To Reproduce
- Schedule an interval which runs a certain number of times (inside an effect).
- Update a state value inside that interval.
- Ensure that you are using setState update function pattern. Although the other pattern also works, this one is easy for logs.
const useTypewriter = () => {
const [count, setCount] = useState(0);
useEffect(() => {
let i = 0;
// console.log("called");
const interval = setInterval(() => {
console.log({ i });
if (i < 5) {
setCount((count) => {
console.log("inside callback");
return 0 + i;
});
console.log("now"); //Initially this logs after "inside callback", but after two iterations it logs before "inside callback"
i++;
} else {
clearInterval(interval);
}
}, 200);
return () => {
clearInterval(interval);
};
}, []);
console.log({ count });
};
Link to code example: https://codesandbox.io/p/sandbox/amazing-rain-forked-5knv6z?workspaceId=ws_XcXHczGEnBvM34o6MyJMXt
The current behavior
In the initial iteration the setState callback is called synchronously but later it is called asynchronously.
The expected behavior
setState to behave same in all iterations.