Why class-recipe
class-recipe solves the same problem as class-variance-authority and tailwind-variants: turning component props into class names. Its config looks like theirs, so moving over is mostly mechanical. It differs in four ways:
- It styles components of several elements with slots, which class-variance-authority does not have.
- A variant without a default is required by its type, so a component cannot forget to choose it.
- It resolves conflicting classes with any join function, such as
twMerge, and caches the result, so the join runs once per selection. - It is faster: it prepares each config once and caches the class name of each selection, so most calls are a lookup.
class-recipe 1.7.2 |
class-variance-authority 0.7.1 |
tailwind-variants 3.3.1 |
|
|---|---|---|---|
| Slots | Yes | No | Yes |
| Variant without a default | Required by its type | Optional | Optional |
| Conflict resolution | Any join function, cached | Call twMerge on the result |
tailwind-merge, built in |
| Extending a recipe | composes |
No | extend |
| Recipe calls per second, without merging | 13.4 million | 1.4 million | 1.0 million |
tailwind-variants has two builds. Its main entry point merges classes
with tailwind-merge. Its lite build, tailwind-variants/lite, does
not merge classes, and does not need tailwind-merge. The calls per second
above measure the lite build, so that every library does the same work.
They come from the benchmarks,
which also measure each library with tailwind-merge.
When the speed matters
Section titled “When the speed matters”One recipe call is fast in every one of these libraries. For a page with a few buttons, you will not notice the difference. The cost adds up when a recipe runs many times per second:
- Large lists. A table, a feed, or a grid with hundreds of rows calls several recipes for each row, on every render.
- Frequent re-renders. A component that renders on each keystroke, scroll event, or animation frame calls its recipes each time.
- Merging classes on every call. A
cn(button(props))helper, which passes each result totwMerge, runs tailwind-merge on every render. tailwind-merge does much more work than joining strings. A recipe of class-recipe created withcreateRecipes({ join: twMerge })runs it once for each selection, then reads its cache. In the benchmarks, it runs 4× as many calls per second as class-variance-authority withtwMergeon every result.
A faster recipe leaves more of each frame to the rest of your app. It cannot make a slow component fast, though: measure your app before you optimize it.
Next steps
Section titled “Next steps”- Migrating from class-variance-authority and Migrating from tailwind-variants move your recipes over.
- Benchmarks shows every measurement and how it was made.