From 585a37c6597650f2c71c27c2e4078fb966b73d3e Mon Sep 17 00:00:00 2001 From: Trevor Burnham Date: Sat, 24 Jan 2026 17:34:13 -0500 Subject: [PATCH] perf: memoize highlight result to avoid redundant tokenization The highlight function performs expensive tokenization on every render, even when content hasn't changed. This adds useMemo to cache the result based on content and highlight function, preventing unnecessary re-tokenization during parent re-renders, dark mode toggles, or action button interactions. --- src/code-view/internal.tsx | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/code-view/internal.tsx b/src/code-view/internal.tsx index 978f69f..e21835d 100644 --- a/src/code-view/internal.tsx +++ b/src/code-view/internal.tsx @@ -1,6 +1,6 @@ // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 -import { Children, createElement, Fragment, ReactElement, useRef } from "react"; +import { Children, createElement, Fragment, ReactElement, useMemo, useRef } from "react"; import clsx from "clsx"; import { useCurrentMode } from "@cloudscape-design/component-toolkit/internal"; @@ -50,8 +50,8 @@ export function InternalCodeView({ const regionProps = ariaLabel || ariaLabelledby ? { role: "region" } : {}; const accessibleLineNumbers = lineNumbers && i18nStrings?.lineNumberLabel && i18nStrings?.codeLabel; - // Create tokenized React nodes of the content. - const code = highlight ? highlight(content) : textHighlight(content); + // Memoize tokenized React nodes to avoid re-running highlight on every render. + const code = useMemo(() => (highlight ? highlight(content) : textHighlight(content)), [content, highlight]); // Create elements from the nodes. const codeElementWrapper: ReactElement = createElement(Fragment, null, code); const codeElement = Children.only(codeElementWrapper.props.children);