react icon indicating copy to clipboard operation
react copied to clipboard

Bug: When setState is called with the same value as before, memory goes up

Open arturcarvalho opened this issue 1 year ago • 0 comments

The issue seems to be, when I change a state variable with setState, and if I do setState(x) and x is the same as the current state variable inside a useInterval hook, the memory starts to grow. I'm using usehooks-ts but I also tried with other hooks (Dan Abramov's hook and Josh Comeau's hook)

This is the code causing the issue:

  const [charge, setCharge] = useState<number>(0);

  function updateRemainingCharge() {
    setCharge((prev) => {
      const sameValue = maybeTrue(0.99999);
      return sameValue ? prev : prev + 1;
    });
  }

  useInterval(updateRemainingCharge, 5);

  const [charge, setCharge] = useState<number>(0);

But if I do:

  const maybeTrue = (odds: number) => Math.random() < odds;
  const toSym = (num: number) => Symbol(num);
  const fromSym = (sym: Symbol) => Number(sym.description);
  
  const [charge, setCharge] = useState<Symbol>(Symbol(0));

  function updateRemainingCharge() {
    setCharge((prev) => {
      const sameValue = maybeTrue(0.99999);
      const num = fromSym(prev);
      return sameValue ? toSym(num) : toSym(num + 1);
    });
  }

  useInterval(updateRemainingCharge, 5);

it doesn't leak. I'm aware I can fix it by stopping the interval, but that seems like an optimization and in my original code the delay was slow, so there was not even a need for immediate optimization.

React version: 18.2.66

Steps To Reproduce

  1. Go to https://ovp-two.vercel.app/
  2. on chrome start to track memory, check the memory going up while the number doesn't change

Link to code example: https://github.com/arturcarvalho/op

Link to deployed code: https://ovp-two.vercel.app/

I don't know how to debug memory leaks on codesandbox, it seems to hide them.

The current behavior

Memory goes up when setState(x) where x is the same as current x on state variable.

The expected behavior

Memory not go up when setState(x) where x is the same as current x on state variable.

arturcarvalho avatar May 03 '24 05:05 arturcarvalho