useFetchis sufficient. However, sometimes you may want to take full control, for example if you want to combine multiple requests. In this case you can use the
useAsync(and React Async in general), is the
promiseFn: a function that returns a
Promise. It's the fundamental concept for modelling asynchronous operations. It enables React Async to take control over scheduling, the Promise lifecycle and things like (re)starting an operation on user action or other changes. We've deliberately chosen the
Promiseas our primitive, because it's natively supported and has various utility methods like
Promise.all. That's also why you'll find our terminology closely follows the Promise states and fates.
useAsync, would look like this:
promiseFnwill be invoked with a
propsobject and an
propsare the options you passed to
useAsync, which is why you can access the
idproperty using object destructuring. The
AbortControlleris created by React Async to enable abortable fetch, so the underlying request will be aborted when the promise is cancelled (e.g. when a new one starts or we leave the page). We have to pass its
fetchin order to wire this up.