useAsyncEffect
Runs an async effect and supports async cleanup.
Runs an async effect and supports async cleanup.
Import
import { useAsyncEffect } from '@kamod-ch/hooks'Live demo
Basic demo
Runs an async effect and supports async cleanup.
Status: idle
import { useState } from 'preact/hooks'
import { useAsyncEffect } from '@kamod-ch/hooks'
export default function UseAsyncEffectDemo() {
const [query, setQuery] = useState('kamod')
const [status, setStatus] = useState('idle')
useAsyncEffect(async () => {
setStatus('loading')
await new Promise((resolve) => window.setTimeout(resolve, 500))
setStatus('loaded for ' + query)
}, [query])
return (
<div>
<input value={query} onInput={(event) => setQuery(event.currentTarget.value)} />
<p><strong>Status:</strong> {status}</p>
</div>
)
}
API
TypeScript signature
import type { DependencyList } from '../utils/types-compat.js';
declare function useAsyncEffect(effect: () => AsyncGenerator<void, void, void> | Promise<void>, deps?: DependencyList): void;
export default useAsyncEffect;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.