Home > Mobile >  Best way to link CSS styles in React
Best way to link CSS styles in React

Time:08-05

First of all, about my question, I have to explain that I organize my CSS folder in diferents folders and files, so each CSS file has a purpose and I can make changes or solve problems easily. Then I import all these files into a main.css file, which I link in the HTML header.
So, by now, I'm learning React. I see that the usual is to import the CSS file inside the component, but I tried to do that inside the index.html and it's working.
By the way, I use Vite and it creates a single CSS file that works perfectly.
My question is: this is really properly or should I import inside each component the CSS file that it will need, so I should delete the main.css file? I feel some worried about the performance.
I post here below an example of my main.css file, so you can check the way I work usually:

/* main.css */

/* base */
@import './base/normalize.css';
@import './base/reset.css';
@import './base/global.css';

/* layout */
@import './layout/footer.css';
@import './layout/header.css';
@import './layout/navigation.css';

/* components */
@import './components/button.css';
@import './components/headers.css';
@import './components/banner.css';
@import './components/works.css';
@import './components/card.css';

/* pages */
@import './pages/index.css';
/*@import './pages/article.css';*/

/* utils */
@import './utils/fonts.css';
@import './utils/utilities.css';
@import './utils/variables.css';

CodePudding user response:

You are right to worry about the performance issue caused by unused CSS. It is always better to load required js, css, and other files and functions only when the component that requires those features is loaded. In order to test the difference in performance, you can follow this guide to understand how your web app is in terms of speed, structure, best practices, etc.: Lighthouse

I would also suggest going through React lazy loading for code-splitting and learning about webpack plugins that you could use such as CSSMinimizerWebpackPlugin, and others.

  • Related