---
name: fix-3g
description: Catch and fix UI flashes, layout shifts, and broken loading states that are invisible on fast localhost but break on real 3G/4G networks: fake empty-state flashes ("No items yet" / "$0.00" before API resolves), unsized image CLS, webfont FOUT/FOIT reflow, hydration dead-zone clicks while JS downloads, and SSR-to-hydration theme or auth-bar flashes. Works on any React, Next.js, Vue, Svelte, Astro, or plain HTML app.
license: MIT
metadata:
  author: Hairline UI
  url: https://hairlineui.com/skills/fix-3g
  version: "1.0.0"
---

# /fix-3g

Find and fix every flash, layout jump, and dead click that is invisible on `localhost` (where assets and API calls resolve in 4ms) but hits real users on cold-cache 3G/4G connections.

This skill is **zero-redesign and zero-lock-in**. It does not change your visual design, colors, or component library — it only fixes loading states, reserved geometry, font metrics, and hydration seams so slow networks look intentional instead of broken.

## Guardrails (never break these)

- **Never add artificial `setTimeout` delays or fake splash screens** to hide loading states. Fix the actual layout reservation, pending-state logic, and pre-paint styling.
- **Keep genuinely empty states intact.** A brand-new user with 0 records *should* see an empty state once `status === 'success'` and `data.length === 0` — just never while `isPending` / `isLoading` is still true.
- **Do not replace `<a href>` links with `<button onClick>`** — native anchor links already work before JavaScript hydrates.
- **Never add external libraries** to solve CSS geometry, font metrics, or loading-state booleans.
- **Never report a fix you did not re-verify under cold-cache Slow 3G in Chromium.**

---

## Step 1 — Measure the baseline under cold-cache Slow 3G

### 1A. Run the Chromium Slow-3G verifier (recommended)

With your local dev server running, fetch and run the verifier across your key routes. It disables browser cache via Chrome DevTools Protocol (`Network.setCacheDisabled`), emulates Slow 3G, and deterministically stalls JS, fonts, images, and API calls so localhost-invisible flashes surface immediately:

```bash
curl -sL https://hairlineui.com/skills/fix-3g-check.mjs -o /tmp/fix-3g-check.mjs
node /tmp/fix-3g-check.mjs http://localhost:3000 --routes /,/dashboard,/pricing
```

*(Pass `--click "button[data-testid='menu']"` to test a specific SSR button during the pre-hydration JS stall, or `--api-delay 1200 --media-delay 600 --js-delay 850` to tune stall durations.)*

Record the 5 baseline numbers before editing:
1. Fake empty-state flashes (visible `"No … / $0"` text that disappears once `fetch`/`xhr` resolves)
2. Media layout shifts (real `PerformanceObserver('layout-shift')` CLS under delayed images)
3. Webfont reflow / FOIT (heading line-wrap jumps or invisible text under delayed cold-cache fonts)
4. Hydration dead-zone clicks (SSR buttons that silently ignore clicks until JS bundles arrive)
5. SSR → hydration flashes (pre-JS theme luminance or header auth-button snaps)

### 1B. Static source scan

Run these from the project root to locate common root causes quickly:

```bash
G='-g *.{tsx,jsx,ts,js,vue,svelte,astro,html} -g !node_modules -g !.next -g !dist'

# 1. Empty-state checks that forget to guard on loading/pending state
rg -n '(\.length\s*===?\s*0|!\s*data\b|!\s*items\b)' $G .

# 2. Raw <img> tags missing width/height or aspect-* reservation
rg -n '<img\b' $G . | rg -v '(width=|aspect-|h-\d|size-)'

# 3. @font-face rules missing font-display: swap/optional or metric overrides
rg -n '@font-face' -g '*.css' -g '!node_modules' -g '!.next' -g '!dist' .

# 4. useEffect reading localStorage/cookies/auth immediately after mount (flash source)
rg -n 'useEffect\s*\([^)]*=>\s*\{[^}]{0,160}(localStorage|document\.cookie|matchMedia|getSession|auth)' $G .
```

---

## Step 2 — Fix each 3G-only defect at its root cause

### 2.1 Fake empty-state & `$0.00` flashes while API is in flight

**Why localhost hides it:** Local API routes respond in 5ms, so `items = []` renders for less than a single frame. On 3G (800–1500ms RTT), users stare at `"No invoices yet"` or `"$0.00"` for a full second before real numbers pop in.

- **Fix:** Separate **pending** from **resolved empty** — never initialize fetched state to `[]` or `0` and immediately render the empty/zero branch:
  ```tsx
  // Bad: flashes "No projects yet" for 1.2s on 3G before /api/projects resolves
  const [projects, setProjects] = useState<Project[]>([]);
  if (projects.length === 0) return <EmptyState />;

  // Good: distinguish pending (null/isPending) from confirmed empty ([])
  const [projects, setProjects] = useState<Project[] | null>(null);
  if (projects === null) return <ProjectsSkeleton count={3} />; // match loaded row height!
  if (projects.length === 0) return <EmptyState />;
  ```
- **Match skeleton geometry to loaded rows:** Give every skeleton card the exact same height, padding, and border radius as the real component so the page doesn't jump when data arrives.
- **Prefer server data / initial props** (React Server Components, loaders, or SSR hydration state) for above-the-fold data so the first HTML paint already has real rows.

### 2.2 Unsized image & media layout shifts (`CLS > 0.05`)

**Why localhost hides it:** Local images decode before first paint. On 3G, an `<img>` without intrinsic dimensions starts at `0px` tall and shoves everything underneath it down 300px half a second later.

- **Fix:** Always reserve exact aspect ratio before a single byte of the image downloads:
  - Set both `width` and `height` HTML attributes on every `<img>` (with `h-auto` if fluid), **or** wrap it in an explicit `aspect-[16/9]` / `aspect-square` / fixed-height container.
  - For hero/LCP images above the fold, add `fetchPriority="high"` and avoid `loading="lazy"` (lazy-loading the hero image delays LCP on 3G).
  - For embeds, charts, avatars, and iframes, declare an explicit `min-h-[...]` or `aspect-*` wrapper so the surrounding text never reflows.

### 2.3 Webfont swap reflow (FOUT) & invisible text (FOIT)

**Why localhost hides it:** Local `.woff2` files load in 1ms from disk. On cold-cache 3G, Chromium either hides text completely (`FOIT` with `font-display: block`) or renders Arial/Times first and wraps headings onto an extra line 600ms later (`FOUT` CLS).

- **Fix:**
  - In Next.js, load fonts with `next/font/google` or `next/font/local` with `display: 'swap'` and `adjustFontFallback: true` (default) so Next generates calibrated `size-adjust`, `ascent-override`, and `descent-override` fallback metrics automatically.
  - In custom `@font-face` CSS, always set `font-display: swap` (or `optional` for non-critical display faces) and add metric overrides (`size-adjust`, `ascent-override`, `descent-override`, `line-gap-override`) on the fallback `@font-face` so the fallback matches the webfont's character width and line height.
  - Preload only the 1–2 primary above-the-fold `.woff2` weights (`<link rel="preload" as="font" type="font/woff2" crossorigin>`).

### 2.4 Hydration dead-zone clicks while JS is downloading

**Why localhost hides it:** Bundles download and hydrate in 40ms locally. On Slow 3G, SSR HTML paints at `300ms`, a user taps a button or menu at `600ms`, and JS doesn't finish hydrating until `1.8s` — the click disappears into thin air.

- **Fix:**
  - **Use native HTML where possible:** Navigation should use `<a href="...">`, forms should use `<form action={...}>`, and disclosure panels/menus can use `<details>/<summary>` so they work at `t = 0` before JS arrives.
  - **For strictly JS-driven controls** (client-only filters, modals, checkout actions): render a clear non-jarring pending/disabled state (`disabled={!hydrated}` or `aria-busy={!hydrated}`) **or** defer non-critical third-party scripts (`analytics`, chat widgets, heavy charts) so main hydration finishes under 400ms on 3G.
  - **Code-split heavy below-the-fold widgets** (`next/dynamic` / `React.lazy`) so the interactive header/hero chunk stays tiny.

### 2.5 SSR → hydration theme & auth-bar flashes

**Why localhost hides it:** Hydration finishes before the user's eye registers the SSR frame. On 3G, the raw SSR frame sits on screen for a full second.

- **Theme flash:** Apply the theme class and `color-scheme` in a tiny synchronous inline `<script>` inside `<head>` before first paint (never inside `useEffect`).
- **Auth-bar flash (`"Sign in"` flashing before switching to the user avatar):** Read the session cookie on the server (or render a neutral fixed-width placeholder slot `w-20 h-9` while auth status is `loading`) instead of defaulting unauthenticated `"Sign in"` buttons on the first client frame when a logged-in user reloads.

---

## Step 3 — Re-verify under cold-cache Slow 3G

1. Run your project's typecheck and production build.
2. Re-run the Slow-3G verifier on the exact same routes:
   ```bash
   node /tmp/fix-3g-check.mjs http://localhost:3000 --routes /,/dashboard,/pricing --fail
   ```
3. Confirm every count dropped to `0` and that genuinely empty states, loaded images, fonts, and buttons all behave cleanly on both fast and slow connections.

---

## Step 4 — Report (keep it tight)

```text
/fix-3g — verified under cold-cache Slow 3G (400ms RTT, uncached assets)

  Fake empty-state flashes:     2 → 0  (distinguished pending vs empty + matched skeleton height)
  Media layout shifts (CLS): 0.24 → 0.00  (reserved aspect-ratio + explicit width/height)
  Webfont swap reflow / FOIT:   2 → 0  (font-display: swap + fallback metric overrides)
  Hydration dead-zone clicks:   1 → 0  (native <a href> / deferred non-critical bundle)
  SSR → hydration flashes:      1 → 0  (server-read auth slot + pre-paint theme script)

Files changed:
- src/components/ProjectsList.tsx — render height-matched skeleton while status === 'pending'
- src/components/HeroMedia.tsx — added aspect-[16/10], width/height, and fetchPriority="high"
- src/app/layout.tsx — added adjustFontFallback metrics and server-hydrated nav slot

Not checked:
- Authenticated routes requiring external OAuth callback
```
