gaearon / react-hot-loader

Tweak React components in real time. (Deprecated: use Fast Refresh instead.)

Home Page:http://gaearon.github.io/react-hot-loader/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

  1. node -v: v10.15.1

  2. npm -v: 6.4.1

  3. Operating system: macOS 10.14.6

  4. 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.