1. What are CSS Modules in React?
When building React applications, styling components is an important part of creating a beautiful and user-friendly interface. But as an application grows, normal CSS files can cause a common problem: CSS class name conflicts.
Imagine two components using the same CSS class name, such as button. If both styles exist in a global CSS file, one component's styling may unintentionally affect another.
CSS Modules solve this problem by making CSS class names locally scoped to a component.
CSS Modules allow us to write normal CSS while ensuring that class names are unique when applied to the application.
2. Why do we need CSS Modules?
Consider this global CSS:
/* styles.css */ .button { background-color: blue; color: white; } If multiple components use .button, the styles can overlap or unintentionally affect other elements.
With CSS Modules, styles are scoped to a specific component, reducing unwanted styling conflicts.
3. How to use CSS Modules in React?
CSS Modules are simple to implement in React projects that support them, such as projects using Vite or Create React App.
Step 1: Create a CSS Module file
Create a file named:
Button.module.css
.button { background-color: #6366f1; color: white; padding: 12px 24px; border: none; border-radius: 8px; cursor: pointer; } .button:hover { background-color: #4338ca; } The .module.css extension tells the supported build system to process the stylesheet as a CSS Module
Step 2: Import the CSS Module into your React component
Create a file named Button.jsx:
import styles from './Button.module.css'; function Button() { return ( <button className={styles.button}> Click Me </button> ); } export default Button; Step 3: Use the component
import Button from './Button'; function App() { return ( <div> <h1>Welcome to React</h1> <Button /> </div> ); } export default App; 5. Advantages of CSS Modules
- Scoped styling: Styles are locally scoped by default.
- No class name conflicts: Generated class names help avoid collisions.
- Reusable components: Each component can maintain its own styles.
- Easy to maintain: CSS remains organized alongside component logic.
- Regular CSS syntax: No need to learn an entirely new styling language.

