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
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
@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.
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.
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.
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.
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.
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.
March 18, 2019 at 11:06am