cn: The Tailwind Merger That Moves the Work Out of React

A deep look at the compiled class-matching engine that replaces runtime parsing with flat tables, typed arrays, and aggressive caching.

10 min read • View on GitHub • More from shadcn-ui

A wide editorial scene shows Tailwind class tokens and conflict rules as a tangled handwritten pile on the left, then a compact mechanical sorter on the right that turns them into one merged output strip. The image explains that cn shifts class conflict resolution from runtime interpretation to a precomputed table-driven system.
cn does not just merge classes faster. It moves the expensive part of the job into a compiled structure before React ever renders.
Key Takeaways

The class helper that stopped interpreting and started compiling

Most class helpers are glorified string glue. cn is different. It takes the Tailwind merging problem, compiles the rules into compact tables, and leaves runtime with a narrow job: look up, scan, return.

That is the real surprise in this repo. It does not try to make class merging a little faster in the old shape. It changes the shape.

cn produces the same output as tailwind-merge for every input. We verify this with 356,000 differential tests.

shadcn-ui/cn Documentation, Official Project Docs · shadcn-ui/cn GitHub Repository

Why Tailwind class merging is secretly expensive

Tailwind makes class strings expressive, but it also creates a conflict system. If a component receives p-2 and later adds px-4, the merge layer has to know which rule wins. Add variants, responsive prefixes, conditional branches, and repeated React renders, and the work stops being trivial.

This is why the old pattern exists in so many codebases: clsx builds the string, then tailwind-merge resolves the conflicts. It works well, but it still interprets Tailwind semantics at runtime.

import { clsx } from "clsx";
import { twMerge } from "tailwind-merge";

export function cn(...inputs: Parameters<typeof clsx>) {
  return twMerge(clsx(inputs));
}
ToolWhat it doesWhere the Tailwind logic livesRuntime cost
clsxConditionally concatenates classesNowhere, it does not know Tailwind semanticsLow
tailwind-mergeResolves Tailwind class conflictsRuntime parser and merge logicHigher
clsx + twMergeCommon hand-rolled cn patternSplit between two librariesHigher
cnSingle package with compiled conflict tablesMostly build time, then fast lookupLower

The key idea is not that Tailwind rules disappear. They are simply paid for earlier.

The compiler: where Tailwind rules become tables

The compiler in compiler.ts is where the project earns its compiler label. It takes nested class-group definitions, validators, and conflict rules, then flattens them into structures the runtime can traverse cheaply. The repository description calls out a radix trie and conflict adjacency lists, which is exactly the kind of transformation that turns human-readable semantics into machine-friendly lookup data.

The interesting move is not the trie itself. It is that the trie becomes a compact artifact the browser never has to build from scratch.

// Conceptual shape, not exact source
const compiled = buildCompiler({
  classGroups,
  conflictingClassGroups,
  validators,
});

// Runtime uses integer lookups instead of rebuilding rules
const merged = cnRuntime(input, compiled);

This is why the article’s core claim matters. cn is not a faster interpreter. It is a compiler that ships the result.

The runtime: one pass, no allocations, minimal drama

The runtime in engine.ts is built for the common case: strings that repeat, class fragments that do not change much, and UI code that reruns often. Instead of splitting strings into objects and maps, it scans character by character and uses typed arrays like Int32Array and Uint8Array as pointer-like structures.

That matters because allocations are not free. Fewer temporary objects means less garbage collection pressure, and that usually matters more than a flashy benchmark headline. If the engine can return the original string reference, it avoids doing work entirely.

A close-up editorial scene shows a narrow stream of incoming class strings passing through a cache gate. Most of the stream exits immediately through a fast bypass lane, while only a small branch descends into a tiled trie built from typed arrays. The image explains why repeated inputs are fast before the engine even starts traversing conflict rules.
The runtime is fast partly because repeated inputs never reach the heavy machinery.

The cache story is what keeps the speed claims from feeling magical. cn assumes UI code behaves like UI code: it repeats itself.

Why the cache layers matter more than the benchmark headline

The best performance ideas usually fit the workload instead of fighting it. cn does that by stacking shortcuts around the patterns React teams already have: the same component trees, the same class combinations, the same prop-driven branches.

LayerWhat it avoidsWhy it helps
Argument cacheRe-checking identical argument listsStable references can short-circuit immediately
Sequence learningWalking the same merge path repeatedlyCommon render loops become cheaper after the first pass
Whole-string cacheRecomputing completed mergesFinal outputs can be reused directly

That is a better story than a raw speed number. The benchmark matters, but the real design insight is that the library treats repetition as the default, not the exception.

How cn compares to clsx, tailwind-merge, and the old pattern

The ecosystem view is straightforward. clsx is good at assembly. tailwind-merge is good at Tailwind conflict knowledge. The old cn pattern glues those together. This project collapses the stack and moves the intelligence out of the hot path.

PackageStrengthWeaknessBest use case
clsxTiny and fastNo Tailwind conflict logicConditional class assembly
tailwind-mergeUnderstands Tailwind rulesDoes its work at runtimeConflict resolution only
clsx + twMergeFamiliar and flexibleTwo libraries, more runtime workCommon app-level helper
cnCompiled tables plus cachingMore specialized under the hoodTeams that want parity with less runtime cost

The practical tradeoff is not simplicity versus power. It is whether you want the runtime to interpret Tailwind on every render, or whether you want that interpretation prepaid.

What this says about the direction of frontend tooling

cn fits a broader pattern in frontend infrastructure. The more predictable a UI problem becomes, the more often its expensive parts can be extracted, precomputed, and stored in compact data structures. That is a compiler instinct applied to app code.

It also suggests something narrower but useful: mature UI tooling is starting to treat repeated renders as a systems problem. Once you do that, optimizations like table flattening, typed arrays, and aggressive caching stop looking exotic and start looking obvious.

Check out cn by shadcn for an even faster cn package. cnfast will no longer be maintained in favor of cn. I recommend you go use that package instead!

Aiden Bai, Co-author of cn / Creator of Million.js · aidenybai/cnfast GitHub Readme

That is where cn lands best. It is a utility, but it is also a signal: if the problem is stable enough, move the work out of React and into a compiler.

Source authors and implementation context

The project is co-authored by shadcn and Aiden Bai. The repository structure centers on packages/cn/src/compiler.ts, packages/cn/src/engine.ts, and generated tables, with conformance tests that compare output against tailwind-merge across a large fuzz corpus.

That testing posture is important. A faster class merger is only useful if it keeps the exact same behavior people already depend on.