Skip to content

Bug: setState inside setInterval runs async first and then sync #32265

Closed as not planned
@TusharShahi

Description

@TusharShahi

React version: 19

Steps To Reproduce

  1. Schedule an interval which runs a certain number of times (inside an effect).
  2. Update a state value inside that interval.
  3. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Resolution: StaleAutomatically closed due to inactivityStatus: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions