menu

styled-components

Visual primitives for the component age. Use the best bits of ES6 and CSS to style your apps without stress!

Channels
Team

Does Styled Components Use Memoization?

March 16, 2019 at 8:30am

Does Styled Components Use Memoization?

March 16, 2019 at 8:30am (Edited 1 month ago)

For example, if I render a list of 100 items, does styled components re-parse the CSS for each item even if it is only a text label that changes for each item, or does it memorize the generated styles?


March 16, 2019 at 10:41am

Do you mean memoization?

  • reply
  • like

And I believe that it only reparses CSS related props. Anything that is just set as a static attribute shouldn't impact anything. I could totally be wrong, though

  • reply
  • like

@tbhesswebber sorry, yes that is what I meant. Think it got autocorrected on my phone. Trying to debug some performance issues when hydrating a page in Gatsby. Looks like SC is repeatedly reparsing the CSS each time a component is rendered, despite their styles being identical for all items which I was pretty surprised about.

Edited
  • reply
  • like

I've been experimenting using fast-memoize to memoize helpers, but it feels like this should be happening at the SC level as well or instead of memoizing helper functions.

  • reply
  • like

It appears that if I use a function within an SC interpolation, that function is called once for every component, even if all sc-related props are identical.

  • reply
  • like

March 17, 2019 at 9:20am

Memoization is by the browser's css engine when component is styled via className. Inline styling is where the real performance bottleneck could exist if you have millions of items, then browser would use a lot of memory and freeze each time it would clean its memory cache. CSS classes solve that. As far as rendering plaintext css in the JS engine + calculating hash for classname, this both takes milliseconds so it is not a factor. The bottleneck is usually caused by the memory trashing or graphics redraws.

  • reply
  • like

In short, don't worry about it, you can performance test the loop in a realistic scenario, and if it is below 200ms it is not perceivable for a human. Premature optimization is the source of most bugs.

  • reply
  • like

If your CSS is static, we only parse it once and then never again. If your CSS has dynamic interpolations we have to parse it every time. We cannot memorize that, because props can change somewhere deeply nested.

  • reply
  • like

In fact, @alansouzati recently tried to add memorization to that part of the codebase and did not notice any performance difference!

  • reply
  • like

March 18, 2019 at 11:06am

Would using React.memo work out the box? I've not tried this myself.

const MemoComponent = React.memo(styled.div)`
background-color: ${props => props.backgroundColor};
`
Edited
  • reply
  • like