Nuxt & Universal SSR (50 Qs)•Part 2: Core Architecture & Data Fetching (Mid-Level)
What is the difference between `useFetch()` and `useAsyncData()`?
senior LevelCode ExampleAsync & PromisesSystem DesignHTTP & REST APIs
In Simple Words:
useAsyncData()is the foundational wrapper that manages asynchronous SSR serialization, caching keys, loading states, and hydration reconciliation for any promise.useFetch(url)is a convenient syntactic sugar built directly on top ofuseAsyncData()and$fetch. It automatically generates an internal cache key based on the URL and query parameters.
Comparison Matrix:
| Feature | useFetch(url, options) | useAsyncData(key, handler) |
|---|---|---|
| Primary Use | Direct HTTP endpoints | Any custom async logic (DB calls, multi-API join, SDKs) |
| Cache Key | Auto-generated from URL | Manually supplied string key |
| Reactivity | Automatically re-fetches when reactive query changes | Requires watch option or manual refresh() |
typescript
// useFetch: Simple HTTP endpoint
const { data: user, pending, error, refresh } = await useFetch('/api/user', {
query: { id: userId }
});
// useAsyncData: Complex promise aggregation
const { data: dashboard } = await useAsyncData('dashboard-data', async () => {
const [stats, notifications] = await Promise.all([
$fetch('/api/stats'),
$fetch('/api/notifications')
]);
return { stats, notifications };
});