Open keshidong opened 5 years ago
useState's return value can get setState(s) val before executed next render function. The race-condition about accessing s can be solved for some cases.
setState(s)
s
const [loading, setLoading] = useState(false) const fetchList = async () => { if (loading) return setLoading(true) await fetch(`url`) setLoading(false) }
In this example, if fetchList be called frequently, the fetchList that loading as false may be called multiple times.
fetchList
loading
false
This is because setLoading may be asynchronous, updating the fetchList that loading as true is not such fast, or atomic.
setLoading
true
Expect:
const [loading, setLoading, isLoading] = useState(false) const fetchList = async () => { if (isLoading()) return setLoading(true) await fetch(`url`) setLoading(false) }
isLoading is function and does not depend on the render function must be executed before the fetchList is called next time.
isLoading
useState's return value can get
setState(s)
val before executed next render function. The race-condition about accessings
can be solved for some cases.In this example, if
fetchList
be called frequently, thefetchList
thatloading
asfalse
may be called multiple times.This is because
setLoading
may be asynchronous, updating thefetchList
thatloading
astrue
is not such fast, or atomic.Expect:
isLoading
is function and does not depend on the render function must be executed before thefetchList
is called next time.