0

1.

const [count, setCount] = useState(0); setCount(count+1); 

OR

2.

const [count, setCount] = useState(0); setCount(count => count+1); 

I am confused as to when should I be using the two ways of updating state in my component and what difference does it have? Thanks.

6
  • 1
    Check this stackoverflow.com/questions/42038590/… Commented Apr 8, 2020 at 3:48
  • @hussain.codes No the link is about the class component's component.setState() method. But the OP's asking about useState() returned function. Passing callback to the two meanings very different things. Commented Apr 8, 2020 at 4:08
  • 1
    @hackape the concept is same, whether you are using functional or class Component, if your new state is dependent on the old state use functional update. that's the concept. Commented Apr 8, 2020 at 4:14
  • 1
    @hussain.codes Well. I just realized the .setState(cb1, cb2) method can accept two callbacks. cb1 is the same concept. Before I always have the impression that its signature is .setState(partialState, cb). Commented Apr 8, 2020 at 4:19
  • @hussain.codes No, this question is not about using callbacks after setting state, it is about the actual updating of state. Completely different concept. Commented Apr 8, 2020 at 4:30

1 Answer 1

6

Use option 1 when the new state is independent of the previous state, like fetching data from a server and you are simply replacing current state.

Use option 2 when the next state depends on the current state, like incrementing a count.

BTW, option 2's pattern is called a functional update since you pass it a pure function that takes the current state, mutates it, and returns the next state.

The following is a counting demo I've created to really show the difference between the two and why the distinction is important.

const [count, setCount] = useState(0); /** * count +3 click handler using naive state updates. */ 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 }; /** * count +3 click handler using functional state updates. */ 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 }; 

Edit react - bad and good state updates

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.