Search code examples
javascriptreactjssettimeout

Updating a variable during asynchronous function time out


const [value, setValue] = useState(0);
const counter = () => {
  setTimeout(() => {
    // setValue(value + 1);
    setValue((prevState) => prevState + 1);
  }, 2000);
};

counter is called when a button is pressed i.e.

<button onClick={counter}>counter</button>

Why does setValue(value + 1) update the value once if I press the button multiple times, but setValue((prevState) => prevState + 1) return the correct value relative to the amount pressed?


Solution

  • State updates are not always immediate. Using the previous value ensures that you are working with the current value at the point in time where the value is being set. Kent Dodds explains this well in this post. Bigger question might be, why are you wrapping this in a setTimeout?