简体   繁体   中英

Can't understand how passing function to update state hook works

In the following code:

// create state count
const [count,setCount] = useState(0)

//update state 
setCount(count-1)
setCount(count-1)

The value of count decreases by one only, because setCount() is an asynchronous function. I understand this. But why does the following code work fine, ie count is decreased by two when a function is passed instead of a statement?

setCount(prevCount => prevCount-1)
setCount(prevCOunt => prevCount-1)

Why does the same behaviour as in the first case not appear here? I have limited experience with async functions and am new to react. Thanks for reading!

The value of count decreases by one only, because setCount() is an asynchronous function

No. It is decreased by 1 even with two setCount calls because you pass count - 1 to both function calls. In both calls, you are passing the same value.

Reason why count is not updated after the first setCount call is because state is constant within a particular render of a component. Component can't see the updated state until it re-renders.

If the value of count is 5, then the following

setCount(count-1)
setCount(count-1)

is like

setCount(5 - 1)
setCount(5 - 1)

Why does the same behaviour as in the first case not appear here?

That's because when you pass a function to setCount , prevCount is the most recent value of count . In this case, you are not subtracting 1 from the same value of count .

If the value of count is 5, then the following

setCount(prevCount => prevCount-1)
setCount(prevCount => prevCount-1)

is like

setCount(5 => 5 - 1)
setCount(4 => 4 - 1)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM