Skip to content

Conversation

@TrevorBurnham
Copy link

This PR adds useMemo to cache the syntax highlighting result in the CodeView component, preventing expensive re-tokenization on every render.

Problem

The highlight function (which uses ace-code's tokenizer) runs on every render of InternalCodeView, even when content hasn't changed. This is wasteful because:

  • Tokenization is O(n) where n is the content length
  • It creates many React elements (one span per token, per line)
  • Parent re-renders trigger unnecessary re-computation
  • Common interactions like hovering action buttons or toggling dark mode cause re-tokenization

Solution

Wrap the highlight call in useMemo with [content, highlight] as dependencies:

const code = useMemo(
  () => (highlight ? highlight(content) : textHighlight(content)),
  [content, highlight]
);

Testing

  • All existing unit tests pass
  • No changes to component behavior or API

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

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.
@TrevorBurnham TrevorBurnham requested a review from a team as a code owner January 24, 2026 22:40
@TrevorBurnham TrevorBurnham requested review from SpyZzey and removed request for a team January 24, 2026 22:40
@TrevorBurnham TrevorBurnham changed the title perf: memoize highlight result to avoid redundant tokenization refactor: memoize highlight result to avoid redundant tokenization Jan 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant