Skip to content
LATEST

🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.

Upgradix
Upgradix Code. Learn. Ship.
Updated Nov 25, 2026

Styling in React – CSS Modules, Utility Classes & Themes

Use CSS Modules to scope styles to one component without class name clashes, or Utility Classes for fast inline-like layout. Pair them with CSS Custom Properties (design tokens) to switch between light and dark themes cleanly.

Styling in React – CSS Modules, Utility Classes & Themes

Quick Answer: Use CSS Modules to scope styles to one component without class name clashes, or Utility Classes for fast inline-like layout. Pair them with CSS Custom Properties (design tokens) to switch between light and dark themes cleanly.

Imagine Meena runs a hospital appointment portal in Hyderabad. Her React app has booking cards, lab report tables, and pharmacy bills.

One day, a junior developer adds a .card class to style the Pharmacy Bill. Suddenly, every doctor appointment card on the home page breaks its layout.

How does Meena keep component styles isolated, toggle active or disabled slots cleanly, and support both Light and Dark Mode?

1. Why Global CSS Breaks in Growing React Apps

The problem without scoped styling

In plain CSS, every class name lives in one global namespace. When two files define the same class name, the last file loaded wins.

Example 1: Two global CSS files colliding

This works when Meena has 2 screens, but breaks as soon as the team grows.

/* AppointmentCard.css */
.btn { background: #4F46E5; padding: 12px; }

/* PharmacyBill.css (loaded later, overwrites .btn everywhere!) */
.btn { background: #DC2626; padding: 4px; }

What happens in the browser

Appointment "Book Slot" button turns tiny and red!
Fixing PharmacyBill.css accidentally breaks LabReports.jsx.

This setup works on day one. However, it becomes a maintenance trap.

  1. Class names collide across unrelated components.
  2. Developers become afraid to delete old CSS rules.
  3. Switching between light and dark mode requires duplicating hundreds of color rules.

The solution: Scoped Styles + Design Tokens

CSS Module = a CSS file named *.module.css where Vite automatically generates unique, collision-free class names.

Design Token = a reusable CSS variable (like --color-surface) that stores colors, spacing, or fonts in one central place.

Live Stage: CSS Modules, States & Theme Tokens in Meena's Hospital App

Watch how design tokens and scoped classes update Dr. Arjun's 10:30 AM slot card across themes and states.

DOM & Token Inspector Light · Default
data-theme "light"
--surface #F8FAFC
--accent #4F46E5
className slotBtn_8x2q
Dr. Arjun Rao Cardiology · Hyderabad
Light Mode
10:30 AM – Book Slot
State: Available disabled: false
1. Light · Default
2. Light · Active
3. Dark · Active
4. Dark · Disabled
Scoped CSS Module CSS Token Variable Live DOM Value Active Preview Step

Notice that switching data-theme changes --surface and --accent automatically. The component code stays untouched.

2. CSS Modules – Scoped Styles Without Clashes

When you name a file SlotCard.module.css, React imports its classes as a JavaScript object. Vite rewrites .slotBtn into a unique hash like .slotBtn_8x2q.

Example 2: Scoped styles in SlotCard.module.css

These styles apply only to SlotCard.jsx and never leak to other pages.

.card {
  background: var(--surface);
  color: var(--text);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 16px;
}

.slotBtn {
  border: 2px solid var(--accent);
  background: transparent;
  color: var(--accent);
  padding: 10px 14px;
  border-radius: 8px;
  cursor: pointer;
}

.active {
  background: var(--accent);
  color: var(--accent-text);
}

.slotBtn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

3. Toggling Active & Disabled States Cleanly

In React, you toggle visual states by combining class names conditionally based on props or state.

Example 3: Toggling active and disabled states in SlotCard.jsx

Always pair visual disabled styles with the real HTML disabled attribute for accessibility.

import styles from "./SlotCard.module.css";

export function SlotCard({ time, isSelected, isBooked, onSelect }) {
  // Join base class with conditional active class
  const btnClass = [
    styles.slotBtn,
    isSelected ? styles.active : ""
  ].filter(Boolean).join(" ");

  return (
    <div className={styles.card}>
      <button
        type="button"
        className={btnClass}
        disabled={isBooked}
        aria-pressed={isSelected}
        onClick={onSelect}
      >
        {isBooked ? `${time} - Slot Full` : `${time} - Book Slot`}
      </button>
    </div>
  );
}

Using .filter(Boolean).join(" ") keeps the DOM clean with no stray spaces. Adding aria-pressed tells screen readers when a slot is selected.

4. Utility Classes – Fast Styling Right in JSX

Utility Class = a tiny, single-purpose CSS class (like p-4 or rounded-lg) made popular by Tailwind CSS.

Instead of jumping between .jsx and .css files, Meena can style a slot button directly in JSX.

Example 4: The same button using utility classes

Notice how active and disabled states are handled inline with clear utility classes.

<button
  disabled={isBooked}
  className={`px-4 py-2 rounded-lg font-semibold border-2 transition ${
    isSelected
      ? "bg-indigo-600 text-white border-indigo-700"
      : "bg-transparent text-indigo-600 border-indigo-600"
  } disabled:opacity-50 disabled:cursor-not-allowed`}
>
  10:30 AM - Book Slot
</button>

Utility classes speed up UI work and keep bundle sizes small because unused classes are stripped during build.

5. Light/Dark Themes with Design Tokens

The cleanest way to build themes in React is with CSS Custom Properties. Define your light palette on :root and override only the changed values under [data-theme="dark"].

Example 5: Central design tokens in tokens.css

Every component reads these variables instead of hard-coding hex colors.

:root {
  --surface: #F8FAFC;
  --text: #0F172A;
  --border: #CBD5E1;
  --accent: #4F46E5;
  --accent-text: #FFFFFF;
}

[data-theme="dark"] {
  --surface: #111827;
  --text: #F8FAFC;
  --border: #374151;
  --accent: #38BDF8;
  --accent-text: #0F172A;
}

Example 6: Switching themes cleanly in React

Updating one attribute on document.documentElement repaints the entire app without re-rendering every child.

import { useEffect, useState } from "react";

export function ThemeToggle() {
  const [theme, setTheme] = useState("light");

  useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
  }, [theme]);

  return (
    <button onClick={() => setTheme(theme === "light" ? "dark" : "light")}>
      Switch to {theme === "light" ? "Dark" : "Light"} Mode
    </button>
  );
}

6. Global CSS vs. CSS Modules vs. Utility Classes

Comparing React styling approaches
Approach Best For Main Trade-off
Global CSS Resets, fonts, and root design tokens. Class names collide in medium or large apps.
CSS Modules Clean separation of CSS and JSX with zero clashes. More files to switch between while coding.
Utility Classes Fast UI building and consistent spacing/colors. Long className strings in JSX if not extracted.

The important terms to remember

  • CSS Modules = locally scoped CSS files that hash class names automatically.
  • Utility Classes = single-purpose classes composed directly in JSX.
  • Design Tokens = semantic CSS variables (like --surface) that power themes.

Design tip: Name tokens by their role (--surface, --accent), never by their color (--white, --blue). That way, Dark Mode still makes sense when --surface becomes dark slate.

7. Common Mistakes to Avoid

1. Using inline style={{}} for hover, focus, or media queries

React inline styles cannot use pseudo-classes like :hover, :disabled, or responsive breakpoints.

Better approach: Use CSS Modules or utility classes for layout and states. Reserve style={{}} only for dynamic values like a progress bar width.

2. Putting theme colors inside React Context instead of CSS variables

Passing a JavaScript theme object through React Context forces every consuming component to re-render when the user toggles Dark Mode.

Better approach: Store theme values in CSS Custom Properties and toggle a single data-theme attribute on <html>.

3. Styling disabled buttons without the HTML disabled attribute

Adding a gray class alone only hides the button visually. Keyboard users can still press Tab and Enter to book a full slot.

Better approach: Always set the native disabled={isBooked} attribute alongside your disabled styling.

8. Interview Questions & Practice

Question 1: Why are CSS Modules safer than regular CSS imports in React?

What the interviewer expects: Understanding of global CSS leakage and build-time class hashing.

Strong answer: "Regular CSS imports share one global scope, so a .btn class in PharmacyBill can accidentally break Meena's AppointmentCard. CSS Modules scope styles locally by generating unique class names at build time, so components never collide."

Question 2: How would you implement Light and Dark Mode in a large React app without performance lag?

What the interviewer expects: Using CSS Custom Properties (design tokens) rather than re-rendering the entire component tree.

Strong answer: "I define semantic CSS variables like --surface and --accent on :root and override them under [data-theme="dark"]. When the user clicks the toggle, React updates one attribute on the root HTML element, and the browser repaints instantly without re-rendering every component."

What interviewers expect at different levels

  • Junior developer: Knows how to import a CSS Module and toggle an active class with a ternary operator.
  • Senior developer: Builds accessible active/disabled states (disabled, aria-pressed) and avoids Context re-renders for theming.
  • Technical architect: Designs a multi-brand design-token system using semantic CSS variables that works across CSS Modules and utility classes.

Beginner: UPI payment status pill

Create a StatusBadge.module.css with .success, .pending, and .failed classes, and apply the right class based on a status prop.

Expected result: Green pill for "Paid", amber for "Pending", and red for "Failed" with zero global class leaks.

Intermediate: Food delivery cart checkout button

Build a checkout button that switches between an active indigo style when items exist and a disabled muted style when the cart is empty.

Hint: Use disabled={cartCount === 0} and style .checkoutBtn:disabled.

Advanced: Persist Light/Dark theme across reloads

Upgrade Meena's ThemeToggle component so it remembers the user's choice in localStorage and respects prefers-color-scheme: dark on first visit.

  • Read saved theme from localStorage inside useState initializer.
  • Fall back to window.matchMedia("(prefers-color-scheme: dark)") if nothing is saved.

Challenge: Prevent a white flash on page reload by setting data-theme before React mounts.

9. Next Steps

  • Refactor one component in your current Vite project from global CSS to a .module.css file.
  • Add a tokens.css file with 4 semantic variables and wire up a Light/Dark toggle button.

Discussion & Comments

0
Guest mode · Login / Register
Post directly as a guest or log in first.

No comments yet

Start the discussion above — ask a question, share a tip, or reply to a comment.

This article is protected. Printing and saving as PDF are disabled.