Why render styled-components on the server-side at all?

Therefore we should take a closer look at styled-components and especially how it actually works.

Thanks to the library we write our CSS code directly in JavaScript. This has many advantages but is problematic from a performance point of view.

It is the same problem as with classic client-side rendering.

Since everything is only available in JavaScript, but the browser only understands CSS, which can be integrated and understood e.g. by inline-styling, the style-tag, or external CSS files, when executing our web app, the CSS is generated directly with the execution of JavaScript.

Only after this process, the CSS code is readable for the browser, but not immediately, as when we simply write CSS in the head area.

So let’s just keep in mind that CSS-in-JS solutions always need one more step — this of course has a bad effect on performance, even if only minimal.

Here is an interesting benchmark about styled-components vs. native CSS.

Let’s create a new Next.js project first

To use Next.js with styled-components we need a new, basic project.

mkdir <project-name>
cd <project-name>

npm init -y 
npm install react react-dom next styled-components
mkdir pages 

Make sure to update the package.json, so we can actually run and build our project:

“scripts”: {
 “start”: “next start”,
 “dev”: “next dev”,
 “build”: “next build”,
 “export”: “next export”

Let’s create the index.js as our starting page. It should be placed right inside the /pages directory, which serves as the default directory for routes in Next.js.

export default () => (
    <p>This is our next.js app</p>

If you now start the development mode, with “npm run dev”, the app should be working fine.

#nextjs #web-development #react #javascript #styled-components

Server-side-Rendering Styled components with Next.js
16.00 GEEK