Performance: Global CSS
Global CSS affects the initial page load speed and rendering performance by applying styles broadly across the entire app, impacting CSS parsing and style calculation.
// Use CSS Modules or scoped styles for components // styles/Button.module.css .button { background-color: blue; color: white; padding: 1rem; } // components/Button.js import styles from '../styles/Button.module.css'; export default function Button() { return <button className={styles.button}>Click me</button>; } // pages/_app.js import '../styles/globals.css'; // minimal global styles only export default function App({ Component, pageProps }) { return <Component {...pageProps} />; }
/* styles/globals.css */ body { font-family: Arial, sans-serif; } button { background-color: blue; color: white; padding: 1rem; } /* many more global styles for all components */ // pages/_app.js import '../styles/globals.css'; export default function App({ Component, pageProps }) { return <Component {...pageProps} />; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Large global CSS file | No extra DOM nodes | Triggers 1 reflow on load due to style recalculation | High paint cost due to broad style application | [X] Bad |
| Scoped CSS Modules per component | No extra DOM nodes | Minimal reflows, only affects scoped elements | Lower paint cost due to limited style scope | [OK] Good |
app/layout.js in the new app directory or pages/_app.js in the pages directory for this purpose.styles.css in app/layout.js?import './filename.css';.app/layout.js snippet:import './globals.css';
export default function RootLayout({ children }) {
return <html><body>{children}</body></html>;
}globals.css sets body { background-color: lightblue; }, what will be the background color of the page?globals.css in app/layout.js applies styles globally, including the body background color.body { background-color: lightblue; } sets the page background color to lightblue.import './globals.css'; inside a React component file instead of app/layout.js. What problem will you most likely face?app/layout.js or pages/_app.js. Importing elsewhere causes errors.globals.css file with base styles and importing it once in app/layout.js ensures consistent global styles.Pass the test and this pattern moves unknown