An open source design system that's fully customizable and agent ready
TypeScript
perf(Markdown): reuse the rendered document when a re-render changes nothing it reads (#7873)
Cindy Zhanga4e3f131aca7
diff --git a/.changeset/markdown-skip-unchanged-rerender.md b/.changeset/markdown-skip-unchanged-rerender.mdnew file mode 100644index 0000000000..01b0b0e2cb--- /dev/null+++ b/.changeset/markdown-skip-unchanged-rerender.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[perf] Markdown skips re-rendering its document when a parent re-renders without changing the text or any rendering prop, so pages that update around a long document stay responsive; a link handler passed as a new function on each render no longer forces that work, and the rendered output is unchanged.++@cixzhangdiff --git a/packages/core/src/Markdown/Markdown.rerender.test.tsx b/packages/core/src/Markdown/Markdown.rerender.test.tsxnew file mode 100644index 0000000000..039f216e98--- /dev/null+++ b/packages/core/src/Markdown/Markdown.rerender.test.tsx@@ -0,0 +1,143 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Markdown.rerender.test.tsx+ * @input Uses vitest, @testing-library/react, Markdown, a synthetic long document+ * @output Tests that an unrelated caller re-render reuses the rendered document+ * @position Performance regression evidence for long documents. Counting+ * renders of a caller-supplied block renderer is deterministic, unlike a+ * timing budget, and fails when Markdown rebuilds every block element on a+ * re-render that changed nothing it reads.+ */++import {useState} from 'react';+import {act, cleanup, fireEvent, render} from '@testing-library/react';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {Markdown} from './Markdown';+import type {MarkdownComponents} from './Markdown';++afterEach(() => {+ cleanup();+});++/** A long, review-style document: headings, prose, lists, a table, code. */+function longDocument(sections: number): string {+ return Array.from({length: sections}, (_, i) =>+ [+ `## Section ${i}`,+ '',+ `Paragraph ${i} with **bold**, *emphasis*, \`code\` and a [link](/docs/${i}).`,+ '',+ `- Point ${i}`,+ ` - Nested point ${i}`,+ `- [x] Done ${i}`,+ '',+ '| Name | Count |',+ '| --- | ---: |',+ `| row ${i} | ${i * 3} |`,+ '',+ '```ts',+ `const value${i} = ${i};`,+ '```',+ ].join('\n'),+ ).join('\n\n');+}++const SECTIONS = 40;++function createCountingComponents(): {+ components: Partial<MarkdownComponents>;+ renders: () => number;+} {+ let count = 0;+ function CountingCode({code}: {code: string; language?: string}) {+ count++;+ return <pre data-testid="code">{code}</pre>;+ }+ return {components: {code: CountingCode}, renders: () => count};+}++describe('Markdown re-render reuse', () => {+ it('does not re-render any block when a caller re-render changes nothing Markdown reads', () => {+ const {components, renders} = createCountingComponents();+ const source = longDocument(SECTIONS);+ let bump: () => void = () => {};+ function Page() {+ const [tick, setTick] = useState(0);+ bump = () => setTick(t => t + 1);+ return (+ <section data-tick={tick}>+ {/* A new link handler each render, as inline callers write it. */}+ <Markdown components={components} onLinkClick={() => {}}>+ {source}+ </Markdown>+ </section>+ );+ }+ const {container} = render(<Page />);+ const document = container.querySelector('[role="document"]');+ const html = document?.innerHTML;+ expect(renders()).toBe(SECTIONS);++ act(() => bump());+ act(() => bump());++ expect(renders()).toBe(SECTIONS);+ expect(container.querySelector('[role="document"]')).toBe(document);+ expect(document?.innerHTML).toBe(html);+ });++ it('re-renders when the text changes', () => {+ const {components, renders} = createCountingComponents();+ const {rerender, getAllByTestId} = render(+ <Markdown components={components}>{longDocument(2)}</Markdown>,+ );+ expect(renders()).toBe(2);+ rerender(+ <Markdown components={components}>+ {`${longDocument(2)}\n\n\`\`\`ts\nconst added = true;\n\`\`\``}+ </Markdown>,+ );+ expect(getAllByTestId('code')).toHaveLength(3);+ expect(getAllByTestId('code')[2].textContent).toBe('const added = true;');+ });++ it('re-renders when a rendering prop changes', () => {+ const {container, rerender} = render(+ <Markdown headingLevelStart={1}>{'# Title'}</Markdown>,+ );+ expect(container.querySelector('h1')).not.toBeNull();+ rerender(<Markdown headingLevelStart={3}>{'# Title'}</Markdown>);+ expect(container.querySelector('h1')).toBeNull();+ expect(container.querySelector('h3')?.textContent).toBe('Title');+ });++ it('calls the latest link handler after a re-render that reused the document', () => {+ const first = vi.fn();+ const latest = vi.fn(() => false as const);+ const {container, rerender} = render(+ <Markdown onLinkClick={first}>{'[go](/next)'}</Markdown>,+ );+ rerender(<Markdown onLinkClick={latest}>{'[go](/next)'}</Markdown>);+ const link = container.querySelector('a');+ expect(link).not.toBeNull();+ const event = new MouseEvent('click', {bubbles: true, cancelable: true});+ act(() => {+ link?.dispatchEvent(event);+ });+ expect(first).not.toHaveBeenCalled();+ expect(latest).toHaveBeenCalledWith('/next', expect.anything());+ expect(event.defaultPrevented).toBe(true);+ });++ it('starts and stops handling link clicks when the handler is added or removed', () => {+ const handler = vi.fn();+ const {container, rerender} = render(<Markdown>{'[go](/next)'}</Markdown>);+ rerender(<Markdown onLinkClick={handler}>{'[go](/next)'}</Markdown>);+ fireEvent.click(container.querySelector('a') as HTMLAnchorElement);+ expect(handler).toHaveBeenCalledTimes(1);+ rerender(<Markdown>{'[go](/next)'}</Markdown>);+ fireEvent.click(container.querySelector('a') as HTMLAnchorElement);+ expect(handler).toHaveBeenCalledTimes(1);+ });+});diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex f8cbdc6f7f..36d8422067 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -41,6 +41,7 @@ import {TableHeaderCell} from '../Table/TableHeaderCell';import {TableHeader} from '../Table/TableHeader';import {TableBody} from '../Table/TableBody';import {mergeProps} from '../utils';+import {useIsomorphicLayoutEffect} from '../hooks/useIsomorphicLayoutEffect';import {useStreamingText} from '../hooks/useStreamingText';import {computeBoundaries, computeSegments} from './streaming';import type {BaseProps} from '../BaseProps';@@ -2122,6 +2123,21 @@ export function Markdown<}: MarkdownProps<Plugins>): React.ReactElement {const t = useTranslator();const LinkComponent = useLinkComponent();+ // Links read the caller's handler when clicked, so a handler recreated on+ // every caller render does not invalidate the memoized document below.+ // Only whether a handler exists changes the rendered links.+ const onLinkClickRef = useRef(onLinkClick);+ useIsomorphicLayoutEffect(() => {+ onLinkClickRef.current = onLinkClick;+ });+ const hasLinkClick = onLinkClick != null;+ const stableOnLinkClick = useMemo<MarkdownProps['onLinkClick']>(+ () =>+ hasLinkClick+ ? (href, event) => onLinkClickRef.current?.(href, event)+ : undefined,+ [hasLinkClick],+ );// Derive the set of source IDs for the parser (stable across renders when sources don't change)const sourceIds = useMemo(() => (sources ? new Set(Object.keys(sources)) : undefined),@@ -2327,19 +2343,80 @@ export function Markdown<return next;}, [display, smoothedLen, maxSpans]);- const cursor: StreamingCursor = {- offset: 0,- boundaries,- active: isStreaming,- };-- // Build citation context — numbers are assigned in encounter order during rendering.- // This is recreated each render so numbering stays consistent with the AST.- const citationCtx: CitationContext | null = sources- ? {sources, numberMap: new Map(), nextNumber: 1, style: citationStyle}+ const contentWidthValue = contentWidth+ ? typeof contentWidth === 'number'+ ? `${contentWidth}px`+ : contentWidth: null;+ // The block document is the expensive part of a long Markdown render. It+ // depends only on these inputs, so a caller re-render that changes none of+ // them returns the same elements and React skips the whole subtree. The+ // cursor and citation numbering are rebuilt inside, from the start of the+ // document, exactly as a full render builds them.+ const renderedBlocks = useMemo(() => {+ if (display === 'inline') {+ return null;+ }+ const blockCursor: StreamingCursor = {+ offset: 0,+ boundaries,+ active: isStreaming,+ };+ // Numbers are assigned in encounter order during rendering.+ const blockCitationCtx: CitationContext | null = sources+ ? {sources, numberMap: new Map(), nextNumber: 1, style: citationStyle}+ : null;+ return blocks.map((block, i) =>+ renderBlock(+ block,+ i,+ blocks.length,+ density,+ headingLevelStart,+ stableOnLinkClick,+ blockCursor,+ blockCitationCtx,+ contentWidthValue,+ contentAlign,+ LinkComponent,+ inlinePlugins,+ components,+ preparedPlugins,+ t,+ headingProjection,+ ),+ );+ }, [+ display,+ blocks,+ boundaries,+ isStreaming,+ sources,+ citationStyle,+ density,+ headingLevelStart,+ stableOnLinkClick,+ contentWidthValue,+ contentAlign,+ LinkComponent,+ inlinePlugins,+ components,+ preparedPlugins,+ t,+ headingProjection,+ ]);+if (display === 'inline') {+ const cursor: StreamingCursor = {+ offset: 0,+ boundaries,+ active: isStreaming,+ };+ // Numbers are assigned in encounter order during rendering.+ const citationCtx: CitationContext | null = sources+ ? {sources, numberMap: new Map(), nextNumber: 1, style: citationStyle}+ : null;const renderedInline = (<spanref={ref}@@ -2357,7 +2434,7 @@ export function Markdown<renderInline(node,i,- onLinkClick,+ stableOnLinkClick,cursor,citationCtx,LinkComponent,@@ -2391,30 +2468,7 @@ export function Markdown<className,style,)}>- {blocks.map((block, i) =>- renderBlock(- block,- i,- blocks.length,- density,- headingLevelStart,- onLinkClick,- cursor,- citationCtx,- contentWidth- ? typeof contentWidth === 'number'- ? `${contentWidth}px`- : contentWidth- : null,- contentAlign,- LinkComponent,- inlinePlugins,- components,- preparedPlugins,- t,- headingProjection,- ),- )}+ {renderedBlocks}</div>);