Skip to content

Commit bd3a42e

Browse files
KJ7LNWEric Wheeler
andauthored
perf: optimize code block rendering performance (#3135)
feat: optimize code block rendering performance Memoize CodeBlock components to prevent unnecessary re-renders: - Add MemoizedCodeContent for syntax highlighted HTML - Add MemoizedStyledPre for container element - Properly type all component props - Reduce React reconciliation work for complex code blocks Signed-off-by: Eric Wheeler <[email protected]> Co-authored-by: Eric Wheeler <[email protected]>
1 parent d27b22f commit bd3a42e

File tree

1 file changed

+42
-8
lines changed

1 file changed

+42
-8
lines changed

webview-ui/src/components/common/CodeBlock.tsx

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -604,16 +604,15 @@ const CodeBlock = memo(
604604

605605
return (
606606
<CodeBlockContainer ref={codeBlockRef}>
607-
<StyledPre
608-
ref={preRef}
607+
<MemoizedStyledPre
608+
preRef={preRef}
609609
preStyle={preStyle}
610-
wordwrap={wordWrap ? "true" : "false"}
611-
windowshade={windowShade ? "true" : "false"}
610+
wordWrap={wordWrap}
611+
windowShade={windowShade}
612612
collapsedHeight={collapsedHeight}
613-
onMouseDown={() => updateCodeBlockButtonPosition(true)}
614-
onMouseUp={() => updateCodeBlockButtonPosition(false)}>
615-
<div dangerouslySetInnerHTML={{ __html: highlightedCode }} />
616-
</StyledPre>
613+
highlightedCode={highlightedCode}
614+
updateCodeBlockButtonPosition={updateCodeBlockButtonPosition}
615+
/>
617616
{!isSelecting && (
618617
<CodeBlockButtonWrapper
619618
ref={copyButtonWrapperRef}
@@ -718,4 +717,39 @@ const CodeBlock = memo(
718717
},
719718
)
720719

720+
// Memoized content component to prevent unnecessary re-renders of highlighted code
721+
const MemoizedCodeContent = memo(({ html }: { html: string }) => <div dangerouslySetInnerHTML={{ __html: html }} />)
722+
723+
// Memoized StyledPre component
724+
const MemoizedStyledPre = memo(
725+
({
726+
preRef,
727+
preStyle,
728+
wordWrap,
729+
windowShade,
730+
collapsedHeight,
731+
highlightedCode,
732+
updateCodeBlockButtonPosition,
733+
}: {
734+
preRef: React.RefObject<HTMLDivElement>
735+
preStyle?: React.CSSProperties
736+
wordWrap: boolean
737+
windowShade: boolean
738+
collapsedHeight?: number
739+
highlightedCode: string
740+
updateCodeBlockButtonPosition: (forceHide?: boolean) => void
741+
}) => (
742+
<StyledPre
743+
ref={preRef}
744+
preStyle={preStyle}
745+
wordwrap={wordWrap ? "true" : "false"}
746+
windowshade={windowShade ? "true" : "false"}
747+
collapsedHeight={collapsedHeight}
748+
onMouseDown={() => updateCodeBlockButtonPosition(true)}
749+
onMouseUp={() => updateCodeBlockButtonPosition(false)}>
750+
<MemoizedCodeContent html={highlightedCode} />
751+
</StyledPre>
752+
),
753+
)
754+
721755
export default CodeBlock

0 commit comments

Comments
 (0)