Stale Closure in Event Handler
0:00A developer built a counter with an auto-increment feature. When you click "Start Auto-Increment", it should increase the count by 1 every second. But users report that no matter how long they wait, the counter only ever shows "1" after starting. Manual increment works fine.
0 flagged
javascriptclick lines to flag bugs
1
function AutoCounter() {2
const [count, setCount] = useState(0);3
const [isRunning, setIsRunning] = useState(false);4
5
const startAutoIncrement = () => {6
setIsRunning(true);7
setInterval(() => {8
setCount(count + 1);9
}, 1000);10
};11
12
const stopAutoIncrement = () => {13
setIsRunning(false);14
// Note: interval not being cleared is a separate issue15
};16
17
return (18
<div>19
<p>Count: {count}</p>20
<button onClick={() => setCount(count + 1)}>21
Manual +122
</button>23
<button onClick={startAutoIncrement} disabled={isRunning}>24
Start Auto-Increment25
</button>26
<button onClick={stopAutoIncrement} disabled={!isRunning}>27
Stop28
</button>29
</div>30
);31
}