15

I'm working on a website using React and Styled Components. However website is very slow on mobile and warnings appears in Google Chrome console:

[Violation] Long running JavaScript task took 305ms

So I found existing topic with this issue and looking for what slows down my app with React Developer Tools. I created new empty page with many rendered items:

import * as React from 'react'
import { render } from 'react-dom'

const items = new Array(5000).fill({ title: 'Title', description: 'This is description.' })

render(
    <>
        {items.map((item, i) => (
            <div>
                <h1>{item.title}</h1>
                <p>{item.description}</p>
            </div>
        ))}
    </>,
    document.getElementById('app')
)

React Dev Tools profiler shows:

enter image description here

However, if I replace React's div, h1 and p with Styled Components Styled.div, Styled.h1 and Styled.p (without any styles):

import * as React from 'react'
import { render } from 'react-dom'
import Styled from 'styled-components'

const items = new Array(5000).fill({ title: 'Title', description: 'This is description.' })

const Item = Styled.div``
const Title = Styled.h1``
const Description = Styled.p``

render(
    <>
        {items.map((item, i) => (
            <Item>
                <Title>{item.title}</Title>
                <Description>{item.description}</Description>
            </Item>
        ))}
    </>,
    document.getElementById('app')
)

Render time will be more than four times longer:

enter image description here

Here is timeline (above is timeline, bellow is detail of one item):

enter image description here

Most of time takes some context consumer:

enter image description here

Is there any way to improve performance with Styled Components? Of course, I have no 5000 items in real app, but items are more complex and not same, so I cannot easily use virtualized/recycled list or lazyloading.

Michal
  • 1,755
  • 3
  • 21
  • 53

1 Answers1

0

Nope.

Styled Components, as a CSS-in-JS solution, is slow because the JS must be parsed before the CSS is generated, and only then the CSS is applied. With a native CSS solution, the browser renders the CSS while the JS is still loading, so it's a lot faster.

Recently I switched a large app from Styled Components to SCSS modules, with great success. You lose the ability of directly injecting variables into your CSS (there are other ways, like defining CSS --variables), but the performance gain made the app run silky smooth.

rodrigocfd
  • 6,450
  • 6
  • 34
  • 68