0

Type 1:

const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(count + 1)}>+</button>

Type 2:

const [count, setCount] = useState(initialCount);
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>

Though the both above code give the same result, what exactly is difference between them and why 2nd method is preferred than the first one

Ori Drori
  • 183,571
  • 29
  • 224
  • 209
Nagaraj
  • 55
  • 1
  • 2
  • 7
  • Does this answer your question? [Why can't I directly modify a component's state, really?](https://stackoverflow.com/questions/37755997/why-cant-i-directly-modify-a-components-state-really) – norbitrial Jan 05 '20 at 18:21
  • 1
    check this [answer](https://stackoverflow.com/questions/54807454/what-is-prevstate-in-reactjs) – Morta1 Jan 05 '20 at 18:43
  • Does this answer your question? [What is prevState in ReactJS?](https://stackoverflow.com/questions/54807454/what-is-prevstate-in-reactjs) – Agney Jan 05 '20 at 18:48

2 Answers2

0

updating state is asynchronous so it is possible that there would be previous value in the "count" state when you're updating it again

0

The difference is that Type 2 has the latest value while Type 1 has the latest value since the last refresh. You'll notice if setCount is called multiple times before any refresh has occurred.

const [count, setCount] = useState(0);
const someFunction => () => {
   console.log(count); //0
   setCount(count + 1); // count will be set to 1 on next refresh
   console.log(count); //still 0
   setCount(count + 1); // count will still be 1  on next refresh since count hasn't been refreshed
   console.log(count); //still 0
   setCount(c => c + 1); // count will be 2 on next refresh since c has the latest value
   console.log(count); //still 0
};
SILENT
  • 3,916
  • 3
  • 38
  • 57