Skip to content
Tutorials Center
My learning

Topics

Lesson 63 of 87 ยท Performance, Security and Ecosystem

Large Lists and Lazy Loading

Render huge lists with virtual scrolling, store big data with shallowRef, lazy-load heavy components with defineAsyncComponent and load images only when needed.

Rendering ten items is easy. Rendering ten thousand is a different problem, and the cost is not Vue's: every list item becomes several DOM nodes, and the browser has to lay out, style and paint all of them. Scrolling gets choppy, memory climbs, and the first render takes seconds. The cure is to do less: show fewer things at once, load less up front, and hold big data in a cheaper shape.

This lesson works through four techniques: virtual scrolling (render only the rows on screen), shallow reactivity for big datasets, lazy components that download when needed, and lazy images. You will build a working virtual list by hand, which also explains how libraries such as vue-virtual-scroller and @tanstack/vue-virtual work. Start with the general ideas in Performance Basics if you have not read them.

Before anything clever: show less

The fastest row is one you never render. Before reaching for virtual scrolling, ask whether the user really needs 10,000 rows at once:

  • Pagination or "load more" buttons keep each page small and are easy to make accessible.
  • Filtering and search let people find the few rows they want.
  • Server-side work. If the data lives on a server, let the server sort, filter and page it, and send only what is on screen.

Virtual scrolling is for the cases where one continuous scrollable list is genuinely the right interface: logs, chat history, spreadsheets, long feeds.

Virtual scrolling in one picture

A scroll container showing 10,000 rows only ever has about ten rows visible. Virtual scrolling keeps the scrollbar honest (a tall inner element has the height of all rows) but renders only the visible slice, plus a few extra rows above and below so scrolling feels smooth. As the user scrolls, the slice moves and the same few DOM nodes are recycled for new data.

flowchart TD
    A["scrollTop (reactive)"] --> B["first = floor(scrollTop / rowHeight) - buffer"]
    A --> C["last = ceil((scrollTop + viewport) / rowHeight) + buffer"]
    B --> D["visible = items.slice(first, last)"]
    C --> D
    D --> E["v-for renders ~15 rows,<br/>each placed at top = index x rowHeight"]

Two computed values turn the scroll position into a small window of items.

This needs one simplifying rule: rows have a fixed, known height. With that, any row's position is just index * rowHeight. (Variable heights are possible, but they require measuring rows, which is why libraries are worth using in real projects.)

A virtual list you can run

The list below holds 10,000 plain rows. scrollTop is a ref updated by the scroll event. Two computed values turn it into the first and last visible index, and a third slices the items. The inner element is as tall as the whole list, and each rendered row is positioned absolutely. Scroll it, or jump to row 5,000, and watch the "DOM rows" number stay small.

Virtual scrolling with 10,000 rows

At the top the page reports rows 1 to 11 and eleven DOM rows, out of 10,000 items. After "Jump to row 5,000" it shows rows 4,997 to 5,010 and fourteen DOM rows. The number of DOM rows stays in the low teens wherever you scroll.

Things worth noticing in the code:

  • key is the item's own id, so as the window slides, Vue moves and recycles the right nodes instead of rewriting them.
  • items is deliberately not a ref. It never changes, so making it reactive would only add cost (more on that next).
  • The scroll handler does almost nothing: it stores a number. All the real work is in computed values that Vue caches.
  • Because scrollTop changes dozens of times per second while scrolling, keep the row component small and cheap. A fixed buffer of a few rows hides the moment when new rows appear.

For production, use a tested library: variable row heights, horizontal and grid virtualization, keyboard support and scrollToIndex are all hard to get right. The idea you just built is what they do underneath.

A virtual list renders only part of the content, so the browser's built-in find (Ctrl+F) cannot see the rest, and screen readers do not know the total unless you tell them (for example with aria-rowcount and aria-rowindex). Weigh that against the speed gain.

shallowRef for big data

By default, ref and reactive are deep: reading a nested object through a reactive parent returns a reactive proxy of it. For a list of 50,000 records, that means up to 50,000 proxies and their dependency tracking, created lazily as the data is touched. When you only ever replace the whole dataset (a fresh API response, a sorted copy), all that tracking is wasted.

shallowRef tracks only the .value assignment. Nested objects stay plain, so they are cheap, and you give up deep change detection. The demo makes the trade-off visible. Both refs hold similar data. isReactive shows whether a row is a proxy, and the counters show what each ref notices.

Deep ref versus shallowRef

Both lists start with the same 50,000 rows. The deep ref reports that a row is a reactive proxy (true) and the shallow one reports false. Mutating row 0 of the deep ref updates its counter to 1 immediately. Mutating row 0 of the shallow ref changes the data but the counter stays at 0, until you press triggerRef (now it shows 1) or replace the array with a new one.

The rule of thumb for shallow refs: treat the data as immutable. To change something, produce a new array (or call triggerRef after an in-place edit, if you must). That is the same style as the map/filter/spread code you would write in any state-management pattern, and it pairs well with big, read-mostly data such as search results, parsed files and chart series. For third-party instances (a map, an editor), markRaw() does the same job per object. See How Reactivity Works for the details of shallowRef, triggerRef and markRaw.

Lazy components

The code for a component you may never show (a chart library, a rich-text editor, a settings dialog) does not need to be in the first download. defineAsyncComponent wraps a loader function that returns a promise. Vue calls it the first time the component is needed, shows an optional loading component while waiting, and an optional error component on failure. With a build tool, the loader is a dynamic import and the bundler splits that file out automatically (see Dynamic and Async Components):

JavaScript
import { defineAsyncComponent } from "vue";

const HeavyChart = defineAsyncComponent({
  loader: () => import("./HeavyChart.vue"),   // downloaded on first use
  loadingComponent: Spinner,
  delay: 200,       // wait 200 ms before showing the spinner, to avoid flicker
  errorComponent: LoadError,
  timeout: 10000,   // give up after 10 seconds
});

In the sandbox there are no separate files to import, so the demo simulates the download with a timer. The loader counts how often it is called, so you can see two properties of async components: the loader runs once (the result is cached), and a failed load is retried the next time the component mounts.

An async component with loading and error states

Press Show chart. The first attempt fails after half a second and the error component appears (Vue also logs the rejected promise to the console, which is expected here). Press Hide, then Show again: the loader runs a second time, succeeds, and the bars appear. Hide and show once more and the counter stays at 2, because the loaded component is cached.

What to make lazy: things behind a click or a route (dialogs, admin pages, editors, charts), and anything heavy that is below the fold. What not to make lazy: anything visible on first paint, because it only adds a request in front of the content the user came for. Lazy routes are the highest-value case; see Build and Load Performance.

Lazy images

Images are usually the heaviest part of a long list or feed. Two habits help.

1. Let the browser do it. The loading="lazy" attribute tells the browser to fetch an image only when it is near the viewport. Always add width and height as well, so the page does not jump when the image arrives:

HTML
<img v-for="photo in photos" :key="photo.id"
     :src="photo.thumbUrl" :alt="photo.description"
     width="320" height="200" loading="lazy">

Do not use loading="lazy" on the main image at the top of the page; it should load as early as possible.

2. Use thumbnails. Send small images in lists and the full-size file only on the detail page. srcset and sizes let the browser pick a suitable size. Both are covered in the HTML images lessons.

If you need custom behavior (a fade-in, or loading backgrounds), a small custom directive built on IntersectionObserver does it. This one is read-only:

JavaScript
const vLazySrc = {
  mounted(el, binding) {
    const observer = new IntersectionObserver(([entry]) => {
      if (entry.isIntersecting) {
        el.src = binding.value;
        observer.disconnect();
      }
    });
    observer.observe(el);
    el._lazyObserver = observer;
  },
  unmounted(el) {
    el._lazyObserver?.disconnect();
  },
};

Used as <img v-lazy-src="photo.url" width="320" height="200" alt="...">. Remember the cleanup in unmounted: observers that are never disconnected leak.

Choosing a technique

Problem First try Then
Thousands of rows in a table or feed Pagination, filters, server-side paging Virtual scrolling
Slow first render of big data Fewer rows, shallowRef v-memo on rows
Large JavaScript download Lazy routes Lazy components (defineAsyncComponent)
Image-heavy pages loading="lazy", width/height, thumbnails IntersectionObserver directive
Third-party object slows reactivity markRaw or shallowRef Keep it outside reactive state

As always, measure before and after each change (see Performance Basics).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does virtual scrolling keep a 10,000-row list fast?

    Only a small window of rows exists in the DOM; the tall spacer element keeps the scrollbar proportional to the whole list.
  2. 2. In the virtual list demo, why is the items array not wrapped in ref()?

    Reactivity is only needed for data that changes. Static data can stay plain.
  3. 3. You store 50,000 records in a shallowRef and run shallow.value[0].done = true. What happens to a computed that counts done rows?

    shallowRef tracks only assignment to .value. Nested mutation is invisible to Vue unless you notify it with triggerRef or assign a new array.
  4. 4. What does defineAsyncComponent do with the result of the loader once it succeeds?

    A successful load is cached. A failed load is not cached, so the next mount tries again.
  5. 5. Which image attribute pair helps the browser delay offscreen images without layout jumps?

    loading="lazy" postpones the download until the image is near the viewport; width and height reserve the space so the page does not shift.

Summary

  • Show less first: pagination, filters and server-side paging beat clever rendering.
  • Virtual scrolling renders only a window of rows computed from scrollTop, a fixed row height and a small buffer; use a library for real projects.
  • Keep static data out of reactivity; use shallowRef (and treat the data as immutable) or markRaw for big or foreign objects.
  • defineAsyncComponent loads heavy components on first use, with loading and error states; the loader runs once.
  • Use loading="lazy", explicit width and height, and thumbnails for images; an IntersectionObserver directive covers custom needs.
  • Measure before and after every change.

Next: shrink and speed up the app itself in Build and Load Performance.