News for hackers. Stuff that matters.
Re:Two custom React hooks by andrewstuart on Friday December 17, 2021 @05:28PM (#29599138)
Briefly - it is because React batches and executes setState calls some time in the future - thus you MUST use a function call to get a non-stale state.

Refer to my more detailed explanation elsewhere in this thread.

Re:Two custom React hooks by Waterluvian on Friday December 17, 2021 @05:32PM (#29599172)
Thanks. I see the example in the docs shows this method. StackOverflow shows many people sharing the same. I’ve never had this problem so I’m probably quite lucky. But it makes complete sense. I’m surprised it’s not called out on the docs page for setState.
Re:Two custom React hooks by andrewstuart on Friday December 17, 2021 @05:39PM (#29599230)
>> I’ve never had this problem so I’m probably quite lucky.

Possibly, but more likely you've had weird bugs that never quite made sense and eventually things seemed to work so you moved on, but what was actually happening was a stale state problem. It's hard to write big React apps using the wrong way to udpate setState without bugs.