Performance: Nuxt data fetching (useFetch, useAsyncData)
This concept affects page load speed and interaction responsiveness by controlling when and how data is fetched and rendered in Nuxt apps.
import { useAsyncData } from '#app' export default { setup() { const { data } = useAsyncData('data', () => $fetch('/api/data')) return { data } } }
export default { async mounted() { this.data = await fetch('/api/data').then(res => res.json()) } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client fetch in mounted() | Low initial DOM nodes | Multiple reflows on data arrival | High paint cost due to delayed content | [X] Bad |
| Server fetch with useAsyncData | DOM ready with data | Single reflow during hydration | Low paint cost, fast LCP | [OK] Good |
| Repeated useFetch calls in watcher | Multiple DOM updates | Multiple reflows | High paint cost, INP delay | [X] Bad |
| useFetch with refresh() | Single DOM update per refresh | Single reflow | Moderate paint cost, better INP | [!] OK |
useFetch and useAsyncData in Nuxt?useFetch behavioruseFetch fetches data from a URL quickly but does not require a key for caching.useAsyncData behavioruseAsyncData needs a unique key to cache the fetched data, allowing more control over data reuse.useAsyncData requires a unique key for caching, useFetch does not. -> Option BuseAsyncData in a Nuxt component?useAsyncDataconst { data, pending } = useFetch('/api/user')
return { data, pending }pending be initially when the component loads?useFetch loading statepending is a reactive boolean indicating if the fetch is still in progress.pendingpending is true until data arrives.const { data } = useAsyncData(() => $fetch('/api/items'))useAsyncData parametersuseAsyncData requires a unique key string as the first argument for caching.useAsyncData. -> Option DuseAsyncData. You want posts to refresh every time the user ID changes. Which approach correctly achieves this?useAsyncDatauserId in the key string ensures posts refetch when userId changes.useFetch doesn't auto-refresh on param change; manual watch is more complex.useAsyncData with a key including the user ID, e.g., useAsyncData(`posts-${userId}`, () => $fetch(`/api/posts?user=${userId}`)). -> Option APass the test and this pattern moves unknown