---
tags: zeta-dom-react
---
# `useAsync`
Gets asynchronous data and refreshes the components once data is ready or error has occurred.
:::info
The value in the first element of the returned array is initially `undefined`.
:::
The callback is called immediately when component is mounted, while the `state` object contains `loading` and `error` property for state control:
```typescript
function Component(props) {
const [content, state] = useAsync(someAsync);
return (
state.loading ?
<Loading /> :
state.error ?
<Error /> :
<div>{content}</div>
);
}
```
## Manual start or reload
To suppress autoload, pass `false` as the second argument and trigger loading by `state.refresh` callback:
```typescript
function Component(props) {
const [content, state] = useAsync(someAsync, false);
return (
<button onClick={state.refresh}>Load</button>
);
}
```
## Reload upon changes
To auto-refresh upon state change, pass a dependency list as the second argument:
```typescript
function Component(props) {
const [value, setValue] = useState(0);
const [content, state] = useAsync(someAsync, [value]);
/* ... */
}
```
## Debounce
<span style="background: lightblue;padding:.25em .75em;border-radius:1em;font-weight:bold">v0.4.0</span>
A debounce parameter can be assigned to reduce calls caused by consecutive updates.
```typescript
function Component(props) {
/* ... */
// debounce by 500 milliseconds
const [content, state] = useAsync(someAsync, [value], 500);
/* ... */
}
```
## Abort signal
<span style="background: lightblue;padding:.25em .75em;border-radius:1em;font-weight:bold">v0.4.6</span>
Now the callback will receive a `AbortSignal` object and will notify abortion when:
- the component has unmounted
- `state.refresh()` is called while the current operation is still in progress
- `state.abort()` is called
```typescript
function Component(props) {
const [content, state] = useAsync(async (signal) => {
const response = await fetch('...', { signal });
return response.json();
});
/* ... */
}
```