Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
arturcarvalho opened this issue May 3, 2024 · 0 comments
Labels
Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug

Comments

@arturcarvalho
Copy link

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 arturcarvalho added the Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug label May 3, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Status: Unconfirmed A potential issue that we haven't yet confirmed as a bug
Projects
None yet
Development

No branches or pull requests

1 participant