labs

remembered skeleton

2026-08-28

remembering the real layout

most skeletons are a different size from the content that lands on top of them, so they trade one layout shift for two: once when the placeholder appears, and again when it is wrong. the fix is not a better guess, it is remembering. a resize observer measures the real box once and keeps it in session storage, so from the second load onward the swap costs nothing.

what to watch

the left column is what every skeleton does, the right one is what this one does, and the caption under each is the part to watch.

take it with you

three steps, and the stage above runs in your own project.

  1. install

    nothing to add. it runs on react alone, 18 or newer.

  2. copy

    2 files, kept together in one folder, skeleton/. the styles travel with them.

    "use client";
    
    import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";
    import "./skeleton.css";
    
    interface Part {
      top: number;
      height: number;
      left: number;
      width: number;
      radius: string;
    }
    
    export interface Box {
      height: number;
      parts: Part[];
    }
    
    export type Shape =
      | { kind: "block"; aspect: string }
      | { kind: "line"; width?: string };
    
    const EXIT_MS = 180;
    
    const KEY = (id: string) => `skeleton:${id}`;
    
    function isBox(value: unknown): value is Box {
      if (typeof value !== "object" || value === null) return false;
      const box = value as Partial<Box>;
      return (
        typeof box.height === "number" &&
        Number.isFinite(box.height) &&
        box.height > 0 &&
        Array.isArray(box.parts)
      );
    }
    
    function recall(id: string): Box | null {
      try {
        const raw = sessionStorage.getItem(KEY(id));
        if (!raw) return null;
        const parsed: unknown = JSON.parse(raw);
        return isBox(parsed) ? parsed : null;
      } catch {
        return null;
      }
    }
    
    function remember(id: string, box: Box): void {
      try {
        sessionStorage.setItem(KEY(id), JSON.stringify(box));
      } catch {}
    }
    
    function measure(root: HTMLElement): Box | null {
      const base = root.getBoundingClientRect();
      if (base.width <= 0 || base.height <= 0) return null;
    
      const parts: Part[] = [];
      const push = (r: DOMRect, radius: string) => {
        if (r.width <= 0 || r.height <= 0) return;
        parts.push({
          top: r.top - base.top,
          height: r.height,
          left: (r.left - base.left) / base.width,
          width: r.width / base.width,
          radius,
        });
      };
    
      for (const el of root.querySelectorAll<HTMLElement>("[data-skel]")) {
        if (el.dataset.skel === "text") {
          const range = document.createRange();
          range.selectNodeContents(el);
          for (const rect of range.getClientRects()) push(rect as DOMRect, "999px");
          range.detach();
        } else {
          push(el.getBoundingClientRect(), getComputedStyle(el).borderRadius);
        }
      }
    
      return parts.length > 0 ? { height: base.height, parts } : null;
    }
    
    export default function Skeleton({
      id,
      loading,
      fallback,
      remember: remembers = true,
      children,
    }: {
      // the key its traced outline is stored under
      id: string;
      loading: boolean;
      // shapes drawn on the first load, before there is anything to trace
      fallback: Shape[];
      // false always draws the fallback, never the traced outline
      remember?: boolean;
      // mark parts to trace with data-skel="block" or data-skel="text"
      children: ReactNode;
    }) {
      const [box, setBox] = useState(() => (remembers ? recall(id) : null));
      const ref = useRef<HTMLDivElement>(null);
      const [held, setHeld] = useState(loading);
    
      useEffect(() => {
        if (loading) {
          setHeld(true);
          return;
        }
        const timer = window.setTimeout(() => setHeld(false), EXIT_MS);
        return () => window.clearTimeout(timer);
      }, [loading]);
    
      useEffect(() => {
        const el = ref.current;
        if (!el || loading || !remembers) return;
        const ro = new ResizeObserver(() => {
          const next = measure(el);
          if (!next) return;
          remember(id, next);
          setBox(next);
        });
        ro.observe(el);
        return () => ro.disconnect();
      }, [id, loading, remembers]);
    
      return (
        <div className="skeleton-swap">
          {held && (
            <div
              className={box ? "skeleton skeleton--traced" : "skeleton skeleton--drawn"}
              aria-busy="true"
              data-remembered={String(Boolean(box))}
              data-leaving={String(!loading)}
              style={box ? { height: box.height } : undefined}
            >
              {box
                ? box.parts.map((part, i) => (
                    <span
                      key={i}
                      className="skeleton-part"
                      aria-hidden="true"
                      style={
                        {
                          "--i": i,
                          top: part.top,
                          height: part.height,
                          left: `${(part.left * 100).toFixed(3)}%`,
                          width: `${(part.width * 100).toFixed(3)}%`,
                          borderRadius: part.radius,
                        } as CSSProperties
                      }
                    />
                  ))
                : fallback.map((shape, i) => (
                    <span
                      key={i}
                      className="skeleton-part"
                      aria-hidden="true"
                      data-shape={shape.kind}
                      style={
                        {
                          "--i": i,
                          ...(shape.kind === "block"
                            ? { aspectRatio: shape.aspect }
                            : { width: shape.width ?? "100%" }),
                        } as unknown as CSSProperties
                      }
                    />
                  ))}
            </div>
          )}
    
          {!loading && (
            <div className="skeleton-real" ref={ref}>
              {children}
            </div>
          )}
        </div>
      );
    }
    
  3. use

    the stage above, exactly as it runs here. the comments mark what to change.

    example.tsx
    "use client";
    
    import { useEffect, useState } from "react";
    import Skeleton, { type Shape } from "./skeleton/Skeleton";
    
    // a guess at the card, drawn before the first real load
    const GUESS: Shape[] = [
      { kind: "block", aspect: "2 / 1" },
      { kind: "line", width: "42%" },
      { kind: "line", width: "88%" },
    ];
    
    function Card() {
      return (
        <article className="skel-lab-card">
          <span className="skel-lab-art" data-skel="block" />
          <strong data-skel="text">arc reel</strong>
          <p data-skel="text">the curve behind the home carousel.</p>
        </article>
      );
    }
    
    export default function SkeletonExample({ latency = 1100 }: { latency?: number }) {
      const [run, setRun] = useState(0);
      const [loading, setLoading] = useState(true);
    
      useEffect(() => {
        setLoading(true);
        const id = window.setTimeout(() => setLoading(false), latency);
        return () => window.clearTimeout(id);
      }, [latency, run]);
    
      return (
        <div className="skel-lab">
          <div className="skel-lab-cols">
            <section className="skel-lab-col">
              <h3>guessed</h3>
              <Skeleton id="guess" loading={loading} fallback={GUESS} remember={false}>
                <Card />
              </Skeleton>
              <p className="skel-lab-caption">this line moves.</p>
            </section>
    
            <section className="skel-lab-col">
              <h3>remembered</h3>
              <Skeleton id="remembered" loading={loading} fallback={GUESS}>
                <Card />
              </Skeleton>
              <p className="skel-lab-caption">stays put after the first load.</p>
            </section>
          </div>
    
          <button type="button" className="skel-lab-reload" onClick={() => setRun(run + 1)}>
            load again
          </button>
        </div>
      );
    }