react diffrence of set(a) and set(a => a)

What is the difference between case1 and case2?

const [a, setA] = useState(0);

setA(a + 1);      //case 1
setA(a => a + 1); //case 2

>Solution :

  • setA(a + 1); will update from the value of a from the current enclosure.
  • setA(a => a + 1); will update from the previous state’s value

Try enqueueing multiple of either and see the difference.

const clickHandler1 = () => {
  // assume count equals some number n
  setCount(count + 1); // update queued, count === n, count = n + 1
  setCount(count + 1); // update queued, count === n, count = n + 1
  setCount(count + 1); // update queued, count === n, count = n + 1
  // when processed the count will be n + 1
};

const clickHandler2 = () => {
  // assume count equals some number n
  setCount((count) => count + 1); // update queued, count === n + 0, count = prevCount + 1
  setCount((count) => count + 1); // update queued, count === n + 1, count = prevCount + 1
  setCount((count) => count + 1); // update queued, count === n + 2, count = prevCount + 1
  // now when processed each call uses the result of the previous update
  // count will be n + 1 + 1 + 1, or n + 3
};

If the next state depends on any previous state you should use the functional state update. Functional state updates are also handy when enclosing callbacks that update state on intervals or in array loops.

See this working demo:

Edit react - regular and functional state updates

Leave a Reply