Course contentsShow
← React
Lesson 1916 of 2,39644. Styling ApproachesFree lesson

Extracting Reusable Class Strings

Creating JavaScript constants or variables to store repeated utility combinations and maintain DRY principles.

Extracting Reusable Class Strings

What you'll learn: How to avoid repeating the same long utility class combinations by extracting them into JavaScript constants.

When composing Tailwind utilities for complex styles, you often end up with lengthy class strings that appear in multiple components. Writing "flex items-center justify-between px-4 py-2 bg-blue-500 text-white rounded-lg shadow-md hover:bg-blue-600" everywhere creates duplication and makes updates tedious.

The DRY Solution

Instead of repeating these combinations, extract them into JavaScript constants or variables. This keeps your code DRY (Don't Repeat Yourself) and centralizes style definitions:

const primaryButtonClasses = "flex items-center justify-between px-4 py-2 bg-blue-500 text-white rounded-lg shadow-md hover:bg-blue-600";

function ActionButton() {
  return <button className={primaryButtonClasses}>Click Me</button>;
}

function SubmitButton() {
  return <button className={primaryButtonClasses}>Submit</button>;
}

When to Extract

Extract class strings when:

  • The same combination appears in 3+ places
  • The pattern represents a reusable design token (button variants, card styles, etc.)
  • You want centralized control over a specific style pattern

You can organize these in a separate file:

// styles.js
export const buttonPrimary = "px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600";
export const cardBase = "bg-white rounded-lg shadow-md p-6";

This approach works seamlessly with dynamic class composition using clsx when you need conditional variations.

Key Takeaway: Extracting repeated utility combinations into JavaScript constants maintains DRY principles, improves maintainability, and creates a single source of truth for common style patterns in your application.