Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  • 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading