Sub topic 13
Choosing Between Components, Loops, and @apply
This chapter assumes you have read the earlier chapters of this tutorial. You should know utility classes such as flex, px-4, and bg-blue-500, and have used a component framework such as React or Vue, or at least template partials. You have now seen three ways to stop repeating long class lists. This chapter gives you criteria for picking one, and shows what goes wrong when you pick badly.
The three options in one sentence each
- Loop: the markup is repeated because the data is repeated, so write it once and generate it from an array.
- Component: a piece of UI is used in several places, so give it a name, a props interface, and one copy of its markup and classes.
- @apply: a set of utilities has to be attached to an element you cannot or do not want to edit, so give it a CSS class name.
These options are not equal alternatives. A loop and a component both remove duplication from your templates. @apply leaves the duplicated markup in place and moves the class list into a stylesheet, which is why it is the exception and not the default.
Questions to ask, in order
Work through these questions from top to bottom and stop at the first one that applies.
- Is the repetition generated from data? If you are writing the same card five times for five items, you need a loop, not a new abstraction.
- Is it a distinct piece of UI that appears in several places? If it has its own markup and behavior, such as a button, an alert, or a form field, extract a component.
- Is it only a class list on an element whose markup you do not control? Examples are HTML rendered from Markdown, a CMS, or a third-party widget. Use a CSS class with
@apply. - Is it a small set of utilities you want to use like any other utility, with
hover:andmd:support? Define a custom utility with@utility. - Is it only three or four repeats in one file? Edit them together with multi-cursor editing and leave them alone.
Case 1: a loop is enough
Suppose a pricing page shows three plans that share the same card styling. The repetition comes from the data, so the markup should come from the data too.
const plans = [
{ name: "Starter", price: "$9" },
{ name: "Team", price: "$29" },
{ name: "Enterprise", price: "$99" },
];
export function PlanList() {
return (
<ul className="grid gap-4 sm:grid-cols-3">
{plans.map((plan) => (
<li
key={plan.name}
className="rounded-lg border border-gray-200 p-6 shadow-sm"
>
<h3 className="text-lg font-semibold">{plan.name}</h3>
<p className="mt-2 text-3xl font-bold">{plan.price}</p>
</li>
))}
</ul>
);
}The class list appears once, so there is nothing left to deduplicate. Adding a component here would only add a file. Extract one later if the card starts appearing on other pages.
Case 2: a component
Buttons are the classic case. The markup, the classes, and the behavior (disabled state, type, click handlers) belong together, and several pages use them. A component with a variant map keeps every class name written out in full, which Tailwind needs for detection. It also lets callers add overrides safely with tailwind-merge.
import { twMerge } from "tailwind-merge";
const variants = {
primary: "bg-blue-600 text-white hover:bg-blue-700",
secondary: "bg-gray-200 text-gray-900 hover:bg-gray-300",
};
export function Button({ variant = "primary", className, children, ...props }) {
return (
<button
className={twMerge(
"rounded-md px-4 py-2 font-semibold",
variants[variant],
className
)}
{...props}
>
{children}
</button>
);
}A caller can write <Button className="px-8">Save</Button>. Without twMerge, px-4 and px-8 would both appear in the class list, and the winner would depend on the order in the generated stylesheet, not on the order in the attribute. With twMerge, the later px-8 replaces px-4.
Variants must be complete class names
Tailwind finds classes by scanning your source files for complete strings. It does not run your code. This breaks:
// Broken: "bg-red-600" never appears in the source as a whole string.
export function Badge({ color }) {
return <span className={`bg-${color}-600 text-white`}>New</span>;
}The fix is the lookup object you already saw: map each variant name to a full class string.
const colors = {
red: "bg-red-600 text-white",
green: "bg-green-600 text-white",
};
export function Badge({ color = "red" }) {
return <span className={`rounded px-2 py-0.5 ${colors[color]}`}>New</span>;
}Case 3: @apply for markup you do not control
Say a blog renders Markdown into plain <a> and <h2> elements. You cannot put className on them, so a component cannot help. A CSS class can.
@import "tailwindcss";
@layer components {
.article a {
@apply text-blue-600 underline hover:text-blue-800;
}
.article h2 {
@apply mt-8 text-2xl font-bold;
}
}The same approach works for third-party widgets that emit their own class names. Target those names in your stylesheet and apply utilities to them.
Utilities that need variants
If you want a reusable name that behaves like a built-in utility, use @utility in Tailwind CSS v4.
@import "tailwindcss";
@utility btn-base {
@apply rounded-md px-4 py-2 font-semibold;
}Because it is a registered utility, hover:btn-base and md:btn-base work. A class defined only inside @layer components does not give you that.
Scoped stylesheets
In Tailwind v4, a separate stylesheet such as a Vue <style> block does not know your theme or utilities. Import them for reference with @reference.
<style>
@reference "../../app.css";
h1 {
@apply text-2xl font-bold;
}
</style>In Tailwind v3 you could use @apply in such blocks directly. Check which version your project uses before copying an example.
Comparing the options
| Concern | Loop | Component | @apply class |
|---|---|---|---|
| Removes repeated markup | Yes, for data-driven lists | Yes | No |
| Removes repeated classes | Yes | Yes | Yes |
| Works on markup you do not own | No | No | Yes |
| Props and behavior | No | Yes | No |
| Where to read the styling | In the template | In the component file | In the stylesheet, away from the markup |
| Conflict handling | Not needed | `tailwind-merge` | Cascade layers and specificity |
| Variants like `md:` on the name | Not applicable | Not applicable | Only with `@utility` |
Failure modes
Reaching for @apply too early. If your stylesheet fills with .card, .card-title, and .card-footer classes that each hold five utilities, you have rebuilt semantic CSS. You now name things, jump between files, and must remember which class sets what. The component gives you the same reuse while keeping the classes beside the markup.
Overrides that silently fail. Component classes in @layer components sit in a lower cascade layer than utilities, so <div class="card p-8"> lets p-8 win over a padding set by .card. That is usually what you want. Plain CSS written outside any layer beats both layers, so a stray unlayered rule can defeat your utilities. Keep your custom rules inside the layers.
Class merging forgotten. A component that accepts className and just concatenates it will produce conflicting utilities. Use twMerge or restrict overrides to props.
Build cost in scoped styles. In v4, each file that uses @reference gets the theme and utilities made available to it. Many small scoped blocks that use @apply can slow builds. Prefer CSS variables from the theme (for example var(--color-blue-600)) when you only need a value and not a utility.
Splitting over many layers of abstraction. A component wrapping a @apply class that is wrapped by another component is hard to debug. Pick one mechanism for a given piece of UI.
A worked decision
A team has these four situations. The reasoning follows each one.
- A list of 12 blog post cards from an API. This repetition comes from data, so use a loop. If the card also appears on a search page, extract a
PostCardcomponent and loop over it. - A primary button used on 30 screens, with a danger variant. This is a component with a variant map and
twMerge. - Rendered Markdown with links and headings. The markup is not yours, so use
@applyclasses under a wrapper such as.article. - A focus ring recipe you want to write as
focus-visible:ring-recipeormd:ring-recipe. Register a custom utility with@utility, because only that gives you variant support on the name.
Exercise
A teammate has three nearly identical <div> elements, each with 10 utility classes, in one React file, and asks you to move them into a .panel class with @apply. What do you recommend instead, and why?
Show answer
Extract a Panel component, or loop over the data if the panels come from an array. The markup is under your control, so a component removes both the repeated markup and the repeated classes, keeps the styling next to the markup, and can expose variants through props. @apply would only move the class list into the stylesheet.
Exercise
A Badge component builds its classes as ` bg-${color}-100 text-${color}-800 ` and the colors do not appear in production. Why, and how do you fix it?
Show answer
Tailwind scans source files for complete class strings and does not execute your code, so it never sees bg-red-100 or text-red-800. Replace the template string with an object that maps each color name to a full class string, such as { red: "bg-red-100 text-red-800" }, and look the value up by prop.
Exercise
You define .btn-base inside @layer components and then write md:btn-base in your markup. Nothing happens at the md breakpoint. What is the cause and the fix?
Show answer
Classes defined in @layer components are ordinary CSS classes, so Tailwind does not generate variant versions of them. In Tailwind v4, define the name with @utility btn-base { ... }, which registers it as a utility that works with hover:, md:, and other variants.