How to Stream Markdown Tables and Code Blocks Without Layout Shift in React
Streaming Markdown into a React UI commonly causes Cumulative Layout Shift (CLS) and visual jitter because incomplete syntax arrives token-by-token: a half-streamed table row momentarily renders as plain pipe text (| a | b |) before snapping into a <table>, or an unclosed code fence (```ts) jumps height as syntax tokens or line numbers appear and disappear.
- Stabilize incomplete block boundaries during streaming: Markdown tables require a header row and a separator row (
| --- | --- |) to parse as a valid table, and fenced code blocks require a closing```fence. Closing an open code fence virtually for the renderer while streaming—and buffering/stabilizing incomplete table rows—prevents sudden DOM structural swaps. - Lock geometry and reserve space with CSS: Using
table-layout: fixedor explicit column widths,tabular-numsfor numeric columns,overflow-x: autocontainers, and consistent line-height/padding on<pre>and<code>prevents horizontal overflow jumps and vertical height thrashing as lines stream in. - Decouple high-frequency token updates from heavy syntax highlighting: Re-running full AST/syntax highlighting on every single token chunk can stall the main thread or cause highlight flicker; throttle or debounce heavy highlighting slightly (e.g., every 50–100ms while streaming) and run a final full pass when the stream completes.
Steps to Stream Tables and Code Blocks Smoothly in React
- Normalize incomplete fences and buffer trailing table lines while streaming: While
isStreamingis true, append a virtual closing fence if an odd number of```markers is open, and hold back an incomplete trailing pipe line until a newline arrives so half-formed rows do not flicker. - Style tables with deterministic layout rules: Wrap tables in an
overflow-x-autocontainer, settable-layout: fixed(or predictable column widths) andmin-height/ consistent cell padding, and applyfont-variant-numeric: tabular-numsto numeric columns so numbers do not jitter horizontally as digits stream. - Keep code block container metrics constant across streaming and final states: Ensure the streaming code view and the syntax-highlighted code view share the exact same font family, font size, line height, padding, and border dimensions so swapping from plain text to highlighted spans never shifts surrounding paragraphs.
- Throttle expensive syntax highlighting during active streams: Highlight at a controlled cadence (such as
80msthrottle) while streaming, then immediately render the full syntax-highlighted output on stream completion (isStreaming === false).
TypeScript / React Example: Layout-Stable Streaming Markdown Renderer
import React, { useEffect, useMemo, useRef, useState } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
export interface StreamingMarkdownProps {
rawText: string;
isStreaming: boolean;
}
function useThrottledValue<T>(value: T, delayMs: number, active: boolean): T {
const [throttled, setThrottled] = useState<T>(value);
const lastRunRef = useRef<number>(0);
useEffect(() => {
if (!active) {
setThrottled(value);
return;
}
const now = Date.now();
const remaining = delayMs - (now - lastRunRef.current);
if (remaining <= 0) {
lastRunRef.current = now;
setThrottled(value);
return;
}
const timer = window.setTimeout(() => {
lastRunRef.current = Date.now();
setThrottled(value);
}, remaining);
return () => window.clearTimeout(timer);
}, [value, delayMs, active]);
return throttled;
}
/**
* Stabilizes incomplete fenced code blocks and trailing table rows
* while a stream is still in progress to avoid structural layout shifts.
*/
function stabilizeStreamingMarkdown(input: string, isStreaming: boolean): string {
if (!isStreaming) return input;
let text = input;
// If the last line looks like an unfinished table row without a trailing newline,
// hold it back until the line finishes so partial pipes don't flash as text.
const lines = text.split("\n");
const lastLine = lines[lines.length - 1] ?? "";
const looksLikePartialTableRow =
!text.endsWith("\n") && lastLine.trimStart().startsWith("|");
if (looksLikePartialTableRow) {
lines.pop();
text = lines.join("\n");
}
// Close an unclosed ``` fence virtually so the code block renders as <pre><code>
// with consistent geometry instead of collapsing or shifting when closed later.
const fenceMatches = text.match(/^```/gm);
if (fenceMatches && fenceMatches.length % 2 === 1) {
text = `${text}\n\`\`\``;
}
return text;
}
export const StreamingMarkdown: React.FC<StreamingMarkdownProps> = ({
rawText,
isStreaming,
}) => {
const displayRaw = useThrottledValue(rawText, 75, isStreaming);
const stabilizedMarkdown = useMemo(
() => stabilizeStreamingMarkdown(displayRaw, isStreaming),
[displayRaw, isStreaming]
);
return (
<div className="stream-markdown-root">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
components={{
table({ children }) {
return (
<div className="table-scroll-container">
<table className="stable-stream-table">{children}</table>
</div>
);
},
th({ children }) {
return <th className="stable-stream-th">{children}</th>;
},
td({ children }) {
return <td className="stable-stream-td">{children}</td>;
},
pre({ children }) {
// Keep pre geometry identical whether syntax highlighting is active or not.
return <pre className="stable-code-pre">{children}</pre>;
},
code({ className, children, ...props }) {
const isBlock = Boolean(className?.startsWith("language-"));
if (!isBlock) {
return (
<code className="inline-code-chip" {...props}>
{children}
</code>
);
}
return (
<code className={`stable-code-block ${className ?? ""}`} {...props}>
{children}
</code>
);
},
}}
>
{stabilizedMarkdown}
</ReactMarkdown>
</div>
);
};
/* Companion CSS enforcing consistent dimensions and preventing layout shift */
.stream-markdown-root {
overflow-anchor: none;
}
.table-scroll-container {
width: 100%;
overflow-x: auto;
margin: 1rem 0;
}
.stable-stream-table {
width: 100%;
min-width: 480px;
table-layout: fixed;
border-collapse: collapse;
font-variant-numeric: tabular-nums;
}
.stable-stream-th,
.stable-stream-td {
padding: 0.5rem 0.75rem;
line-height: 1.45;
text-align: left;
vertical-align: top;
overflow-wrap: anywhere;
border-bottom: 1px solid rgba(128, 128, 128, 0.25);
}
.stable-code-pre {
margin: 1rem 0;
padding: 0.875rem 1rem;
overflow-x: auto;
border-radius: 8px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.875rem;
line-height: 1.5;
tab-size: 2;
}
.stable-code-block {
display: block;
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
.inline-code-chip {
padding: 0.1rem 0.35rem;
border-radius: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 0.875em;
}
Helpful Tips for Production Streaming UIs
- Avoid auto-scrolling on every token if the user scrolls up: Only pin scroll to the bottom when the user is already near the bottom of the viewport, and use
overflow-anchorcarefully so content additions do not yank the user’s reading position. - Use lightweight or incremental highlighters (
refractor/shiki/highlight.jswith throttled updates): Full-document re-highlighting on every SSE chunk wastes CPU on large code blocks; throttling syntax tokenization during streaming keeps frame times smooth (60fps). - Guard against
overflow-wrap: anywhereinside wide multi-column tables: Long tokens like URLs or hashes can stretch narrow fixed columns iftable-layout: fixedlacks sensible column widths or horizontal scrolling—always pair fixed tables with anoverflow-x-autowrapper.
You must log in or register to comment.
