How I Built a Bubble Sort Visualizer in React — No Animation Libraries

Published: (May 9, 2026 at 02:08 PM EDT)
2 min read
Source: Dev.to

Source: Dev.to

Motivation

As a senior React developer I’ve built dozens of algorithm visualizations. Most explanations use static diagrams that only show the final result, leaving you to guess what happens at each step. I wanted to change that—watch the algorithm work in real time, without any external animation libraries.

Implementation

The visualizer is built with plain React functional components:

  • useState for animation state
  • useRef for timeout management
  • CSS‑in‑JS inline styles

The key insight is to pre‑compute all animation steps, then replay them with a simple timeout loop.

bubbleSort function

function bubbleSort(array) {
  const arr = [...array];
  const steps = [];

  for (let i = 0; i  arr[j + 1]) {
        // Perform the swap
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        // Record the state after the swap
        steps.push({
          arr: [...arr],
          comparing: [j, j + 1]
        });
      }
    }
  }
  return steps;
}

Replaying the steps

steps.forEach((step, index) => {
  setTimeout(() => {
    setArray(step.arr);
    setComparing(step.comparing);
  }, index * 120); // 120 ms between frames
});

Visual Legend

  • 🟣 Purple – unsorted elements
  • 🔴 Red – elements currently being compared
  • 🩵 Cyan – elements that are fully sorted

These colors make it immediately obvious which part of the array is still being processed and which part is already in order.

What’s Next

I’m planning visualizations for the following algorithms and data structures:

  • Binary Search
  • Merge Sort
  • Quick Sort
  • Dijkstra’s Algorithm
  • Binary Search Trees
  • Hash Tables

If you’re a React developer and have ideas for better animation patterns, suggestions for the next algorithm, or performance tips, feel free to leave a comment below!

0 views
Back to Blog

Related posts

Read more »