React one css file or one for each component

Viewed 2625

I am wondering if it is better to have one massive css files with comments that break the codes into corresponding sections (e.g. footer, header). Or one css file for each component. E.g. header.css, footer.css? What are the pros and cons?

2 Answers

I don't think the answer is specific to React and is really one of personal preference.

However, I tend to find POD structures easier to work with.

My typical react component uses css modules and looks something like:

# components/Example/styles.module.css
.example {
  background:blue;
}
# components/Example/index.js
import styles from './styles.module.css'

class Example extends React.PureComponent {
  render () {
    return (
      <div className={styles.example}>Example</div>
    )
  }
}

It really depends on a lot of things:

  1. How big is your application/website?

  2. Is this going to be worked on by a team or just yourself?

  3. Is this a hobby project or an actual commercial product?

Single file approach

Pros:

  • All styles are in one file, so you just need to look at the one file.

Cons:

  • This file can grow pretty quickly and become a nightmare to maintain.
  • It might become harder to reason with especially if this is worked out by multiple people.

Modular approach

Pros

  • Easy to reason with as the files are split into its own modules.
  • Component modules can be shared (if done right).

Cons:

  • More files to manage in the long run. Although if you have a build pipeline that should be too much of an issue. Webpack, for example, will handle that nicely.
  • Naming all your CSS appropriately (yes naming can be annoying).
  • Might require more initial setup and configuration. (not sure if you're using any build pipelines or tools).
Related