---
title: Code Comparison
description: A component which compares two code snippets.
icon: git-compare
author:
  name: itsarghyadas
  url: https://github.com/itsarghyadas
mode: wide
---

<PoweredBy
  packages={[
    { name: 'Shiki', url: 'https://shiki.style/' },
    { name: 'Lucide', url: 'https://lucide.dev/' },
  ]}
/>

### Installation

```package-install
npx shadcn@latest add @redpanda/code-comparison
```

<ComponentPreview name="code-comparison-demo" />

## Usage

The Code Comparison component provides a side-by-side view of code changes with syntax highlighting, diff notation, and focus effects:

```tsx expandable
import { CodeComparison } from '@/components/redpanda-ui/code-comparison';

// Basic comparison
const beforeCode = `function greetUser(name) {
  console.log("Hello " + name);
}`;

const afterCode = `function greetUser(name: string): void {
  console.log(\`Hello \${name}!\`);
}`;

export function Example() {
  return (
    <CodeComparison
      beforeCode={beforeCode}
      afterCode={afterCode}
      language="typescript"
      filename="greet.ts"
      lightTheme="github-light-high-contrast"
      darkTheme="github-dark"
    />
  );
}

// With diff notation and focus
const beforeWithDiff = `function calculateTotal(items) {
  let total = 0;
  for (let i = 0; i < items.length; i++) { // [!code --]
    total += items[i].price;
  }
  return total;
}`;

const afterWithDiff = `function calculateTotal(items: Item[]): number {
  let total = 0;
  for (const item of items) { // [!code ++]
    total += item.price;
  }
  return total;
}`;

export function DiffExample() {
  return (
    <CodeComparison
      beforeCode={beforeWithDiff}
      afterCode={afterWithDiff}
      language="typescript"
      filename="calculate.ts"
      lightTheme="catppuccin-latte"
      darkTheme="catppuccin-mocha"
      highlightColor="var(--color-accent)"
    />
  );
}

// With focus highlighting
const beforeFocus = `function processData(data) {
  const result = [];
  for (let item of data) {
    if (item.active) { // [!code focus]
      result.push(transform(item)); // [!code focus]
    }
  }
  return result;
}`;

const afterFocus = `function processData(data: DataItem[]): ProcessedItem[] {
  const result: ProcessedItem[] = [];
  for (const item of data) {
    if (item.active) { // [!code focus]
      result.push(transform(item)); // [!code focus]
    }
  }
  return result;
}`;

export function FocusExample() {
  return (
    <CodeComparison
      beforeCode={beforeFocus}
      afterCode={afterFocus}
      language="typescript"
      filename="process.ts"
      lightTheme="material-theme-lighter"
      darkTheme="material-theme-darker"
    />
  );
}
```

If you want to toggle between light and dark themes, you can use the `theme` prop.

```tsx
<CodeComparison
  beforeCode={beforeCode}
  afterCode={afterCode}
  language="typescript"
  filename="greet.ts"
  lightTheme="github-light-high-contrast"
  darkTheme="github-dark"
  theme="dark"
/>
```

## When to use

Use this decision tree to determine when to use the Code Comparison component:

```mermaid
graph TD;
    A[❓ Need to show code changes?] --> B{Show comparison?};
    B --> C[✅ Use CodeComparison];
    B --> D[⚠️ Use single CodeBlock];

    C --> E[❓ What type of comparison?];
    E --> F[✅ Before/after refactoring];
    E --> G[✅ Version differences];
    E --> H[✅ Tutorial steps];
    E --> I[✅ Bug fix demonstration];

    F --> J[❓ Need to highlight changes?];
    G --> J;
    H --> J;
    I --> J;

    J --> K[✅ Use diff notation];
    J --> L[ℹ️ Simple side-by-side view];

    K --> M[❓ Need focus areas?];
    L --> M;

    M --> N[✅ Add focus annotations];
    M --> O[ℹ️ Basic comparison without focus];

    N --> P[❓ Custom highlight color needed?];
    O --> P;

    P --> Q[✅ Set highlightColor prop];
    P --> R[ℹ️ Use default theme colors];

    classDef recommended fill:#4ade80,stroke:#22c55e,stroke-width:2px,color:#000;
    classDef discouraged fill:#fbbf24,stroke:#f59e0b,stroke-width:2px,color:#000;
    classDef decision fill:#60a5fa,stroke:#3b82f6,stroke-width:2px,color:#fff;
    classDef neutral fill:#9ca3af,stroke:#6b7280,stroke-width:2px,color:#fff;

    class C,F,G,H,I,K,N,Q recommended;
    class D discouraged;
    class A,B,E,J,M,P decision;
    class L,O,R neutral;
```

### Use Cases

- **Code refactoring**: Show improvements, optimizations, or modernization changes
- **Tutorial content**: Step-by-step code evolution in learning materials
- **Code reviews**: Visual diff for pull requests or code discussions
- **Bug fixes**: Demonstrate problem code vs. solution
- **Migration guides**: Show old vs. new API usage patterns
- **Documentation**: Compare different approaches or versions

### Code Comparison vs Other Components

- **Use Code Comparison when**: You need to show side-by-side code changes with visual diff highlighting
- **Use regular CodeBlock when**: Displaying single code examples without comparison needs
- **Use diff utilities when**: You need inline diff view or text-based comparison
- **Use Tabs when**: Switching between entirely different code examples, not comparing changes

## Anatomy

The panels stack on small screens and sit side by side from the medium breakpoint.
Each panel has a filename header and its own scrollable code surface. The central
comparison marker is hidden on small screens.

Shiki loads when highlighting starts. Its notation transformers mark added, removed,
highlighted, and focused lines before sanitized HTML is rendered. Focus annotations
outline the relevant lines; surrounding code stays fully readable without hover, blur,
or reduced opacity. The default highlight surface uses the theme's accent token.

The light example uses GitHub Light High Contrast. The dark example uses GitHub Dark
Default. Both palettes are emitted together unless `theme` explicitly selects one;
the surrounding application theme controls which token colors are painted.
Custom palettes and highlight colors remain your responsibility to check against the
actual background, including diff and highlight washes.

## Props

<div className="flex flex-row gap-x-3">
  <ExternalLink href="https://magicui.design/docs/components/code-comparison" text="Docs" />
</div>

## Credits

- We take our inspiration from [Magic UI](https://magicui.design/docs/components/code-comparison) for the code comparison component and style.
