Home > Back-end >  What happens if two components import the same CSS file in React?
What happens if two components import the same CSS file in React?

Time:09-04

Let's say I have two React components:

import { React } from "react";
import "./styles.css";

function ComponentA() {
  ...
}
export default ComponentA;

import { React } from "react";
import "./styles.css";

function ComponentB() {
  ...
}
export default ComponentB;

Both of these components are importing the same CSS file styles.css. Now let's say that in my app, I'm importing both of these components, so App.js looks something like this:

import { ComponentA } from "./ComponentA";
import { ComponentB } from "./ComponentB";

function App() {
  return (
    <div className="App">
      <ComponentA />
      <ComponentB />
    </div>
  );
}

export default App;

What exactly happens here? Does my app import the same CSS file twice? And if so, do I just make the import on the App.js file instead?

CodePudding user response:

It's as if it was only imported once.

When a module bundler like Webpack sees an import, it puts the following path in the list of files to process, if the path doesn't exist already. The file is only processed once, no matter how many times it's imported.

Note that with React apps, you will often see

import { React } from "react";

in tens or hundreds of files - React isn't created anew hundreds of times. Rather, the module is processed once, and then files that import it are given access to what React has exported.

Importing CSS files works the same way, in that they're only processed once no matter how many times an import exists for them (though they don't really have exports, just side-effects).

If both ComponentA and ComponentB depend on styles.css, feel free to keep importing styles.css in both - it doesn't hurt, and will make things easier to manage when you can see at a glance that both components directly depend on that CSS.

  • Related