Skip to content

Files

Latest commit

 

History

History
33 lines (21 loc) · 573 Bytes

use-state-setter.md

File metadata and controls

33 lines (21 loc) · 573 Bytes

Setting a New Value with useState

Always pass a function that takes the previous state as an argument when setting the new state. Otherwise, it will use the initial state when the component was initialized.

Bad

function MyComponent() {
  const [counter, setCounter] = useState(0);

  ...

  setCounter(counter + 1);
}

Good

function MyComponent() {
  const [counter, setCounter] = useState(0);

  ...

  setCounter((prevCounter) => prevCounter + 1);
}

Refs