Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

perf(notebooks): memoize rows so one edit re-renders one row (#96071)

Sinan Kucukkoseler9e2a6a43e698
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.rowMemo.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.rowMemo.test.ts
new file mode 100644
index 000000000000..7fd9cc4753e4
--- /dev/null
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.rowMemo.test.ts
@@ -0,0 +1,134 @@
+import { act, fireEvent, render } from '@testing-library/react'
+import { createElement, type ChangeEvent } from 'react'
+
+// Monaco cannot run in jsdom; stand in with a plain textarea that honors value/onChange.
+jest.mock('lib/monaco/CodeEditor', () => {
+ // oxlint-disable-next-line no-require-imports
+ const react = require('react') as typeof import('react')
+ return {
+ CodeEditor: ({ value, onChange }: { value?: string; onChange?: (value: string | undefined) => void }) =>
+ react.createElement('textarea', {
+ 'data-attr': 'mock-code-editor',
+ value: value ?? '',
+ onChange: (event: ChangeEvent<HTMLTextAreaElement>) => onChange?.(event.target.value),
+ }),
+ }
+})
+
+// renderNode runs once per row that actually re-renders: the editor memoizes each row and reuses
+// its element while the row's inputs are unchanged, so a reused row never reaches renderNode. Wrap
+// the real implementation in a spy to count, per row, how many rows re-render after an interaction.
+jest.mock('./renderNode', () => {
+ const actual = jest.requireActual('./renderNode')
+ return {
+ __esModule: true,
+ ...actual,
+ renderNode: jest.fn(actual.renderNode),
+ }
+})
+
+import { MarkdownNotebook } from './MarkdownNotebook'
+import { renderNode } from './renderNode'
+
+const renderNodeMock = renderNode as jest.MockedFunction<typeof renderNode>
+
+function reRenderedRowIndexes(): number[] {
+ return renderNodeMock.mock.calls.map(([props]) => props.nodeIndex)
+}
+
+function stubRowRect(row: Element, top: number, height: number): void {
+ Object.defineProperty(row, 'getBoundingClientRect', {
+ configurable: true,
+ value: () => ({
+ bottom: top + height,
+ height,
+ left: 0,
+ right: 500,
+ top,
+ width: 500,
+ x: 0,
+ y: top,
+ toJSON: () => ({}),
+ }),
+ })
+}
+
+describe('MarkdownNotebook row memoization', () => {
+ beforeEach(() => {
+ renderNodeMock.mockClear()
+ })
+
+ it('re-renders only the hovered row, not the whole notebook, on a hover', () => {
+ const { container } = render(
+ createElement(MarkdownNotebook, { value: '# Title\n\nalpha\n\nbravo\n\ncharlie\n\ndelta' })
+ )
+ const rows = Array.from(container.querySelectorAll('.MarkdownNotebook__row'))
+ // title (0), alpha (1), bravo (2), charlie (3), delta (4)
+ expect(rows).toHaveLength(5)
+ rows.forEach((row, index) => stubRowRect(row, index * 100, 100))
+
+ renderNodeMock.mockClear()
+
+ // Hovering a middle row shows that row's inline insert button, so that row re-renders.
+ fireEvent.mouseEnter(rows[2], { clientY: 220 })
+
+ const reRendered = reRenderedRowIndexes()
+ // The hovered row re-rendered to reveal its insert button.
+ expect(reRendered).toContain(2)
+ // The other rows kept their inputs, so they were reused, not re-rendered with the hover.
+ expect(reRendered).not.toContain(0)
+ expect(reRendered).not.toContain(4)
+ })
+
+ it('shows the insert boundary again when hovering after a focused row blurs', () => {
+ // A reused row keeps its cached hover handlers, so the boundary suppression they apply
+ // while a row is focused must come from current state — a handler that closed over the
+ // focused-state of an earlier render would keep suppressing the boundary after blur.
+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title\n\nalpha\n\nbravo\n\ncharlie' }))
+ const rows = Array.from(container.querySelectorAll('.MarkdownNotebook__row'))
+ rows.forEach((row, index) => stubRowRect(row, index * 100, 100))
+ const visibleBoundaries = (): number =>
+ container.querySelectorAll('.MarkdownNotebook__insert-boundary-button--visible').length
+
+ fireEvent.mouseEnter(rows[2], { clientY: 220 })
+ expect(visibleBoundaries()).toBeGreaterThan(0)
+
+ const alpha = container.querySelectorAll(
+ '.MarkdownNotebook__text-block[contenteditable="true"]'
+ )[1] as HTMLElement
+ act(() => alpha.focus())
+ fireEvent.mouseMove(rows[2], { clientY: 220 })
+ expect(visibleBoundaries()).toBe(0)
+
+ // Hover the same row after blur: it last re-rendered while the focus was active, so its
+ // cached handlers are the ones that would hold a stale focused state.
+ act(() => alpha.blur())
+ fireEvent.mouseMove(rows[2], { clientY: 220 })
+ expect(visibleBoundaries()).toBeGreaterThan(0)
+ })
+
+ it('re-renders only the edited row, not the unchanged title or a distant row', () => {
+ const { container } = render(createElement(MarkdownNotebook, { value: '# Title\n\nalpha\n\nbravo\n\ncharlie' }))
+ const textBlocks = Array.from(
+ container.querySelectorAll('.MarkdownNotebook__text-block[contenteditable="true"]')
+ ) as HTMLElement[]
+ // title (0), alpha (1), bravo (2), charlie (3)
+ expect(textBlocks).toHaveLength(4)
+
+ renderNodeMock.mockClear()
+
+ const alpha = textBlocks[1]
+ act(() => {
+ alpha.focus()
+ alpha.textContent = 'alpha edited'
+ })
+ fireEvent.input(alpha)
+
+ const reRendered = reRenderedRowIndexes()
+ // The edited row re-rendered, so the change is not dropped.
+ expect(reRendered).toContain(1)
+ // Its object reference is unchanged, so the title and a distant row are reused, not re-rendered.
+ expect(reRendered).not.toContain(0)
+ expect(reRendered).not.toContain(3)
+ })
+})
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
index 1e836a788e9a..c718cc93d7b3 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.tsx
@@ -573,6 +573,18 @@ class MarkdownNotebookCrashReporter extends Component<{ children: ReactNode }, M
}
}
+function arraysShallowEqual(a: readonly unknown[], b: readonly unknown[]): boolean {
+ if (a.length !== b.length) {
+ return false
+ }
+ for (let index = 0; index < a.length; index++) {
+ if (!Object.is(a[index], b[index])) {
+ return false
+ }
+ }
+ return true
+}
+
export function MarkdownNotebook(props: MarkdownNotebookProps): JSX.Element {
return (
<MarkdownNotebookCrashReporter>
@@ -627,6 +639,12 @@ function MarkdownNotebookEditor({
const [activeRowIndex, setActiveRowIndex] = useState<number | null>(null)
const [activeBoundaryIndex, setActiveBoundaryIndex] = useState<number | null>(null)
const [focusedRowIndex, setFocusedRowIndex] = useState<number | null>(null)
+ // Mirror for updateActiveBoundaryFromRow: a memoized row keeps its cached hover handlers, so
+ // the handler must read the current suppress state through a ref, not its render's closure.
+ const suppressInsertBoundaryRef = useRef(false)
+ useEffect(() => {
+ suppressInsertBoundaryRef.current = focusedRowIndex !== null || !!insertMenu
+ }, [focusedRowIndex, insertMenu])
const [draggingNodeId, setDraggingNodeId] = useState<string | null>(null)
const [dropBoundaryIndex, setDropBoundaryIndex] = useState<number | null>(null)
const [isExternalDragOver, setIsExternalDragOver] = useState(false)
@@ -652,6 +670,12 @@ function MarkdownNotebookEditor({
const listItemRefs = useRef<Record<string, HTMLElement | null>>({})
const tableCellRefs = useRef<Record<string, HTMLElement | null>>({})
const rootEditableInputHtmlByNodeIdRef = useRef<Record<string, string>>({})
+ // Reuse a row's rendered element while its inputs are unchanged. React skips reconciling a child
+ // whose element keeps the same reference, so a keystroke or a hover frame re-renders only the
+ // rows whose inputs changed, not every row in a long notebook.
+ const rowElementCacheRef = useRef<
+ Map<string, { node: NotebookBlockNode; inputs: readonly unknown[]; element: JSX.Element }>
+ >(new Map())
const blockDragNodeIdRef = useRef<string | null>(null)
const isTextSelectionPointerActiveRef = useRef(false)
const floatingToolbarRevealTimeoutRef = useRef<number | null>(null)
@@ -972,6 +996,17 @@ function MarkdownNotebookEditor({
}
}, [setDebugOpen, showDebug])
+ useEffect(() => {
+ // Node ids are content-derived, so an edit gives the changed node a new id and orphans its
+ // old cache entry. Drop entries for ids that no longer exist so the map stays bounded.
+ const liveNodeIds = new Set(document.nodes.map((node) => node.id))
+ for (const nodeId of rowElementCacheRef.current.keys()) {
+ if (!liveNodeIds.has(nodeId)) {
+ rowElementCacheRef.current.delete(nodeId)
+ }
+ }
+ }, [document.nodes])
+
const mapRemoteCaretAnchors = useCallback(
(previousDocument: NotebookDocument, nextDocument: NotebookDocument, remoteMergeVersion?: number): void => {
const anchors = remoteCaretAnchorsRef.current
@@ -4927,7 +4962,7 @@ function MarkdownNotebookEditor({
const updateActiveBoundaryFromRow = (event: ReactMouseEvent<HTMLElement>, rowIndex: number): void => {
setActiveRowIndex(rowIndex)
- if (focusedRowIndex !== null || insertMenu) {
+ if (suppressInsertBoundaryRef.current) {
setActiveBoundaryIndex(null)
return
}
@@ -5994,6 +6029,43 @@ function MarkdownNotebookEditor({
)
}
+ const renderMemoizedNotebookRow = (node: NotebookBlockNode, index: number): JSX.Element => {
+ const rowInsertMenu = insertMenu && insertMenu.nodeId === node.id ? insertMenu : null
+ // Every value renderNotebookRow reads for this row, beyond the node object itself. A reused
+ // row keeps its cached handlers, and each one is safe: it reads refs/state setters/props, or
+ // it reads state captured here (so a change re-renders the row with fresh handlers). Add a
+ // dependency here whenever renderNotebookRow starts reading a new per-row value.
+ const inputs: readonly unknown[] = [
+ index,
+ mode,
+ aiWritingNodeIndexSet.has(index),
+ aiWritingPlaceholderNodeIds.has(node.id),
+ rowInsertMenu ? (rowInsertMenu.mode ?? 'tools') : null,
+ rowInsertMenu ? rowInsertMenu.query : null,
+ rowInsertMenu ? rowInsertMenu.selectedIndex : null,
+ rowInsertMenu ? insertMenuPosition : null,
+ draggingNodeId === node.id,
+ dropIndicatorTarget?.index === index ? dropIndicatorTarget.position : null,
+ selectedComponentNodeIds.has(node.id),
+ activeRowIndex === index,
+ focusAIPromptNodeId === node.id ? (focusAIPromptRequest ?? null) : null,
+ isAIPromptSubmitDisabled,
+ componentPanelCache[node.id],
+ placeholderNodeId === node.id ? placeholder : null,
+ hideResourceLinks,
+ allowViewModeFilters,
+ mergedRegistry,
+ insertCommands,
+ ]
+ const cached = rowElementCacheRef.current.get(node.id)
+ if (cached && cached.node === node && arraysShallowEqual(cached.inputs, inputs)) {
+ return cached.element
+ }
+ const element = renderNotebookRow(node, index)
+ rowElementCacheRef.current.set(node.id, { node, inputs, element })
+ return element
+ }
+
const firstTextGroupKey = renderedNodeGroups.find((group) => group.type === 'text')?.key
return (
@@ -6080,7 +6152,7 @@ function MarkdownNotebookEditor({
const chunkLastIndex = chunk.items[chunk.items.length - 1].index
const rows = chunk.items.map(({ node, index }) => (
<Fragment key={node.id}>
- {renderNotebookRow(node, index)}
+ {renderMemoizedNotebookRow(node, index)}
{chunk.surface === 'text' && index < chunkLastIndex
? renderInsertBoundaryButton(index + 1, {
isGapClickable: false,
@@ -6116,7 +6188,7 @@ function MarkdownNotebookEditor({
return (
<Fragment key={group.key}>
- {renderNotebookRow(group.node, group.index)}
+ {renderMemoizedNotebookRow(group.node, group.index)}
{renderInsertBoundaryButton(group.index + 1)}
</Fragment>
)