Bug: When setState is called with the same value as before, memory goes up
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
- Go to https://ovp-two.vercel.app/
- 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.