DEV Community

Cover image for How I Built a Bubble Sort Visualizer in React — No Animation Libraries
Amar Gul
Amar Gul

Posted on

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

As a Senior React developer I've built dozens
of complex applications — but I wanted to create
something that actually helps people understand
computer science fundamentals visually.

So I built AlgoCanvas — a series of algorithm
visualizations built purely in React.

Why I Built This

Most algorithm explanations use static diagrams
or walls of code. Neither actually shows you
what the algorithm is doing at each step.

I wanted to change that. Watch it work — and
it clicks instantly.

The Tech Stack

  • React functional components
  • useState for animation state
  • useRef for timeout management
  • CSS-in-JS inline styles
  • Zero external animation libraries

How the Animation Works

The key insight is building all animation steps
upfront, then replaying them with setTimeout:

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

  for (let i = 0; i < arr.length - 1; i++) {
    for (let j = 0; j < arr.length - i - 1; j++) {
      steps.push({ 
        arr: [...arr], 
        comparing: [j, j + 1] 
      });
      if (arr[j] > arr[j + 1]) {
        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
        steps.push({ 
          arr: [...arr], 
          comparing: [j, j + 1] 
        });
      }
    }
  }
  return steps;
}
Enter fullscreen mode Exit fullscreen mode

Then replay each step with a delay:

steps.forEach((step, index) => {
  setTimeout(() => {
    setArray(step.arr);
    setComparing(step.comparing);
  }, index * 120);
});
Enter fullscreen mode Exit fullscreen mode

Color Coding System

  • 🟣 Purple — unsorted elements
  • 🔴 Red — currently being compared
  • 🩵 Cyan — fully sorted and done

This makes it immediately obvious what the
algorithm is doing at every single step.

The Result

What's Next

I'm building visualizations for:

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

Subscribe to AlgoCanvas on YouTube if you
want to follow along:
👉 youtube.com/@AlgoCanvas

Feedback Welcome

Would love to hear from other React developers:

  • Better patterns for animation state?
  • Which algorithm should I visualize next?
  • Any performance improvements?

Drop a comment below!

Top comments (0)