keshidong / react-use-that

Basic and powful react hooks
5 stars 0 forks source link

feat: enhance useState #8

Open keshidong opened 5 years ago

keshidong commented 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.

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.

This is because setLoading may be asynchronous, updating the fetchList that loading as true is not such fast, or atomic.

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.