Thuta Learning
Next.js
AdvancedWeb DevelopmentIntermediate

Performance and Accessibility

Next.jsLesson 2340 min

What you'll walk away with

  • Explain what the three Core Web Vitals, LCP, INP and CLS, measure
  • Push "use client" to the leaves of the tree to cut the JavaScript sent to the browser
  • Use next/image and next/font so that loading does not shift the layout
  • Find and fix accessibility problems such as clickable divs, unlabeled inputs and skipped heading levels

Explain it simply

Explain it simply

An app that opens instantly on your new laptop over fast office Wi-Fi is like passing an exam with the answer sheet open. A real user might be in Mandalay on an old phone with a weak 4G signal. Another cannot use a mouse and moves around with the keyboard only, or listens to the page through a screen reader.

Performance means the page appears quickly and responds right away for those people. Accessibility means they can use all of it, whatever device or assistive tool they rely on.

Problem → Why → Solution

The problem: a note card that only works with a mouse and jumps around

The NoteCard below hides two problems. First, the Delete "button" is really a div with an onClick. It works with a mouse, but you cannot reach it with Tab, Enter does nothing, and a screen reader does not announce it as a button.

Second, the img has no width or height, so the browser only learns how much space it needs after the image downloads. At that moment the text below jumps down, and a user aiming for something else may hit Delete by accident. This is called a layout shift.

app/notes/note-card.tsx
"use client"; // the whole card ships to the browser just for one click

export function NoteCard({ note, onDelete }: NoteCardProps) {
  return (
    <div className="card">
      <img src={note.coverUrl} />
      <div className="title">{note.title}</div>
      <div className="btn" onClick={() => onDelete(note.id)}>Delete</div>
    </div>
  );
}

Why is this code a problem?

A div has none of a button's built-in behaviour: no focus, no keyboard activation and no role. An image without alt may be read out by file name, and without a size it adds to CLS. Because the whole card is a Client Component, extra JavaScript ships for a single click. A real button, alt text, explicit dimensions and a well-placed "use client" fix all three.

Core concept: speed as users feel it, and access for every user

Google's Core Web Vitals measure what users experience with three numbers. They are usually judged at the 75th percentile of real visits, so a slow quarter of your users can pull the score down. INP replaced FID as a Core Web Vital in 2024.

MetricWhat it measures"Good" threshold
LCP (Largest Contentful Paint)When the main content appears2.5 s or less
INP (Interaction to Next Paint)Delay from a tap or key to the next frame200 ms or less
CLS (Cumulative Layout Shift)How much the page jumps unexpectedly0.1 or less

Next.js gives you four main levers for these metrics. First, Server Components are the default and send none of their own code to the browser. Keeping "use client" on interactive leaves, such as a like button, shrinks the JavaScript that must download and hydrate, which helps INP. Second, next/image serves properly sized images in modern formats and reserves space from width and height, which protects CLS. Third, next/font downloads fonts at build time, serves them from your own domain and adjusts the fallback font's metrics so lines do not jump when the real font arrives. Fourth, streaming with Suspense shows the rest of the page while slow data is still loading.

The foundation of accessibility is using the right HTML element. Buttons, links, labels and headings come with keyboard, focus and screen reader support for free. A lang attribute on <html> in the root layout (for example "my" for Myanmar) helps screen readers pronounce text correctly. Never hide the focus ring with outline: none without a replacement, and keep text contrast around 4.5:1 for normal-sized text.

Mental model: the old phone and the keyboard user
  1. Send as much as possible as HTML
  2. Put "use client" only on leaves
  3. Reserve space for images and fonts
  4. Try every flow with Tab, no mouse

After each feature, ask: would this work on an old phone over a slow network, without a mouse?

General pattern: a client leaf inside a server page

tsx
import Image from "next/image";
import { InteractiveLeaf } from "./interactive-leaf"; // has "use client"
export default async function Page() { // Server Component
  const data = await getData();
  return (
    <main>
      <h1>{data.title}</h1>
      <Image src={data.imageUrl} alt="Describe the image" width={800} height={450} />
      <InteractiveLeaf id={data.id} />
    </main>
  );
}

The page fetches data and renders HTML on the server. The Image has alt text and dimensions so its space is reserved, and only the small interactive part is split into a client component.

Example: an accessible save button

This SaveButton is a small interactive leaf inside the note page. The page that shows the note stays a Server Component; only this button, which needs state, ships to the client. Notice the real button instead of a div, and the aria-live region.

tsx
"use client";
import { useState } from "react";

export function SaveButton() {
  const [status, setStatus] = useState("idle");
  return (
    <div>
      <button type="button" onClick={() => setStatus("saved")}>
        Save note
      </button>
      <p aria-live="polite">
        {status === "saved" ? "Saved" : ""}
      </p>
    </div>
  );
}

Code breakdown

  1. Client boundary at the leaf"use client";

    The file needs useState and onClick, so it starts with "use client". The page importing it stays a Server Component, so only a little JavaScript reaches the browser.

  2. Local stateconst [status, setStatus] = useState("idle");

    The save status lives inside this component. Changing it from "idle" to "saved" updates the text below.

  3. A real button<button type="button" onClick={() => setStatus("saved")}>

    A button element gets focus with Tab, activates with Enter and Space, and is announced as a "button". type="button" prevents it from accidentally submitting a surrounding form.

  4. A live region for the result<p aria-live="polite">

    When the text inside an aria-live="polite" element changes, the screen reader announces "Saved" after it finishes its current sentence. The p is always rendered on purpose: a region that appears only when the text changes is often missed.

You should see
The app works with both mouse and keyboard, and assistive technology can announce save status.

Reserving space for images and fonts

The Image component from next/image asks for width and height (or fill, to cover its parent). From those it computes the aspect ratio and reserves the space before the image arrives, so nothing shifts. Images below the fold are lazy-loaded by default. For the hero image at the top, which is often the LCP element, ask for early loading with the prop your Next.js version documents (priority, or preload in newer releases).

app/layout.tsx
import { Noto_Sans_Myanmar } from "next/font/google";

const myanmar = Noto_Sans_Myanmar({ subsets: ["myanmar"], weight: ["400", "700"] });

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="my" className={myanmar.className}>
      <body>{children}</body>
    </html>
  );
}

next/font downloads the font files at build time and serves them with your app. The browser never has to contact Google at runtime, and the fallback font is size-adjusted so lines do not jump when the real font takes over.

Measuring and trimming client JavaScript

1. Move "use client" down

"use client" at the top of a layout or page drags everything it imports into the client bundle. Split the interactive part into its own file and put the directive there.

2. Load heavy widgets later

Import components that are not needed right away, such as a chart or a rich text editor, with next/dynamic. They become separate chunks downloaded on demand. The ssr: false option is only allowed inside Client Components.

3. Look at the bundle

A tool such as @next/bundle-analyzer draws which packages end up in each chunk. This is how you usually spot a whole date library or icon pack that slipped in.

A five-minute keyboard check

  • Put the mouse aside and move through the whole page with Tab. You must always see where focus is
  • Focus order must follow the visual order instead of jumping around
  • Every button works with Enter, checkboxes with Space, and modals close with Escape
  • Every input has a visible label, and error messages are linked to their field
  • Headings start at h1 and step down without skipping a level (no h1 followed by h3)

A Lighthouse score of 100 is not the finish line

Lighthouse produces lab data simulated on your machine. Automated accessibility checks catch only part of the problems and cannot answer questions like "does this alt text actually describe the image?". Combine it with field data from real users (Web Vitals) and manual keyboard testing.

In real projects

In real projects

Product teams often set a performance budget: for example, the home page may not exceed a fixed amount of client JavaScript, and LCP must stay under 2.5 seconds at the 75th percentile. When a pull request adds a huge chart library and blows the budget, reviewers see it immediately, long before a customer on a slow connection does.

Accessibility goes on the release checklist too. Once the design system's button, dialog and form field components are made properly accessible, the whole app inherits that work. In areas such as government services and banking, following a standard like WCAG can even be a legal requirement. Many teams also run an automated checker such as axe in CI, then do a short manual keyboard pass before each release.

Common mistakes

Common mistakes

  • Using a div or span with onClick instead of a button. Even with role="button", tabIndex and a hand-written key handler, you are rebuilding what the button element gives you for free.
  • Putting "use client" at the top of the root layout or a whole page. One interactive widget then drags the entire page's code and dependencies into the browser, and the Server Component benefits are lost.
  • Leaving out image dimensions so the layout jumps when the picture loads, or filling alt with meaningless text such as "image". For a purely decorative picture, use alt="" so screen readers skip it.
  • Removing the focus ring with outline: none for looks without adding a replacement focus style. Keyboard users then cannot tell where they are.

Mini challenge

Try it yourself: a tiny accessibility audit

Write an audit function that takes a page's elements as a simple list of objects and reports the problems covered in this lesson. It should find issues on the "before" page and none on the fixed "after" page.

  • Flag an img with no alt attribute at all (alt="" is correct for decorative images)
  • Flag a button with neither text nor aria-label
  • Flag an input with no label linked through htmlFor and no aria-label
  • Flag skipped heading levels (h1 then h3) and any div or span with onClick
a11y-audit.ts
type El = {
  tag: string;
  text?: string;
  alt?: string;
  ariaLabel?: string;
  id?: string;
  htmlFor?: string;
  src?: string;
  onClick?: boolean;
};

export function audit(page: El[]): string[] {
  const issues: string[] = [];
  // TODO: collect the ids that some <label htmlFor> points at
  // TODO: walk the elements and remember the last heading level
  // TODO: push one readable message per problem, e.g. "#3 <input> has no label"
  return issues;
}

// TODO: build a "before" page with problems and a fixed "after" page,
// then print the number of issues and each message for both

Expected: "before: 4 issue(s)" followed by four lines (img without alt, skip from h1 to h3, unlabeled input, clickable div), then "after: 0 issue(s)".

Show hint

Capture the heading level with the regex /^h([1-6])$/. A new level more than one above the previous heading means a level was skipped. Remember to tell alt === undefined apart from alt === "".

Show solution
a11y-audit.ts
type El = {
  tag: string;
  text?: string;
  alt?: string;
  ariaLabel?: string;
  id?: string;
  htmlFor?: string;
  src?: string;
  onClick?: boolean;
};

export function audit(page: El[]): string[] {
  const issues: string[] = [];
  const labels = page.filter((el) => el.tag === "label");
  const labelled = new Set(labels.map((el) => el.htmlFor));
  let lastHeading = 0;

  page.forEach((el, i) => {
    const at = `#${i} <${el.tag}>`;
    const level = /^h([1-6])$/.exec(el.tag);
    if (level) {
      const n = Number(level[1]);
      if (n > lastHeading + 1) {
        issues.push(`${at} skips from h${lastHeading} to h${n}`);
      }
      lastHeading = n;
    }
    if (el.tag === "img" && el.alt === undefined) {
      issues.push(`${at} has no alt attribute`);
    }

    if (el.tag === "button" && !el.text?.trim() && !el.ariaLabel) {
      issues.push(`${at} has no accessible name`);
    }
    if (el.tag === "input" && !el.ariaLabel && !(el.id && labelled.has(el.id))) {
      issues.push(`${at} has no label`);
    }
    if ((el.tag === "div" || el.tag === "span") && el.onClick) {
      issues.push(`${at} is clickable but not a <button>`);
    }
  });
  return issues;
}

const before: El[] = [
  { tag: "h1", text: "Myanmar Notes" },
  { tag: "img", src: "/logo.png" },
  { tag: "h3", text: "Recent notes" },
  { tag: "input", id: "search" },
  { tag: "button", ariaLabel: "Search" },
  { tag: "div", text: "Delete", onClick: true },
  { tag: "img", src: "/divider.svg", alt: "" },
];

const after: El[] = [
  { tag: "h1", text: "Myanmar Notes" },
  { tag: "img", src: "/logo.png", alt: "Myanmar Notes logo" },
  { tag: "h2", text: "Recent notes" },
  { tag: "label", text: "Search notes", htmlFor: "search" },
  { tag: "input", id: "search" },
  { tag: "button", text: "Delete" },
];

for (const [name, page] of [["before", before], ["after", after]] as const) {
  const issues = audit(page);
  console.log(`${name}: ${issues.length} issue(s)`);
  issues.forEach((issue) => console.log(`  - ${issue}`));
}

Quick quiz 1 / 3

Text in a note card jumps down when the cover image finishes loading. Which metric suffers, and what is the fix?

Quick quiz 2 / 3

What is the best way to make <div onClick={remove}>Delete</div> accessible?

Quick quiz 3 / 3

The notes page is a Server Component, and only a like button inside it needs state. Where should "use client" go?

What to remember

  • LCP measures when the main content appears, INP responsiveness, and CLS layout jumps
  • Keep "use client" on interactive leaves to cut client JavaScript
  • Give next/image dimensions and alt text, and self-host fonts with next/font
  • Use real buttons, labels and headings, and test every flow with Tab instead of a mouse

Next.js — Production Checklist — Next.js

Next.js — Production Checklist — Next.js

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.