Smart Code Display
built with: @leafygreen-ui/code
A two-file split that keeps a few hundred KB of highlighter out of First-Load JS without giving up server-rendered code.
The cost being avoided
LeafyGreen's `Code` component pulls in highlight.js and its grammars — hundreds of kilobytes. On a notes-heavy app where nearly every page renders at least one snippet, importing it directly would put that weight in the first-load bundle of essentially the whole site.
But deferring it naively means code blocks render as nothing until JavaScript arrives, which is bad for both perceived speed and readability without JS.
Render plain, then upgrade
The solution is two files. `code-block.tsx` immediately renders the raw code in a styled `<pre>` — real server-rendered HTML, readable with no JavaScript at all, and already using the correct monospace font and box styling so the layout does not jump.
On mount it dynamically imports `code-highlighted.tsx` and swaps it in. Because that import is the only reference to the highlighter, the bundler isolates highlight.js into a separate chunk that is fetched after paint — and never on the server.
The upgrade is visually a colour change on text that was already in the right place, so there is no layout shift.
// src/components/content/code-block.tsx
export default function CodeBlock({ code, language = 'tsx' }: Props) {
const [Highlighted, setHighlighted] = useState<ComponentType<Props> | null>(null);
useEffect(() => {
import('./code-highlighted').then((m) => setHighlighted(() => m.default));
}, []);
if (Highlighted) return <Highlighted code={code} language={language} />;
return (
<pre className="overflow-x-auto rounded-md border border-border bg-background p-3 font-mono text-[13px] leading-relaxed whitespace-pre">
{code}
</pre>
);
}Four languages, two grammars
The public API accepts `jsx`, `tsx`, `javascript`, and `typescript`, but LeafyGreen only knows the latter two. JSX and TSX highlight correctly under the JavaScript and TypeScript grammars respectively, so a small map translates them rather than loading extra grammars.
// src/components/content/code-highlighted.tsx
const LANGUAGE_MAP: Record<CodeLang, Language> = {
jsx: Language.JavaScript,
tsx: Language.TypeScript,
javascript: Language.JavaScript,
typescript: Language.TypeScript
};Important
Gotcha
Where it lives in the repo
- src/components/content/code-block.tsx
- src/components/content/code-highlighted.tsx