Skip to content

Managing highly dynamic styles #134

Closed

Description

@JamieDixon

Example component:

const Comp = styled.div`
     /*lots of styles here*/
     animation-delay: ${ props => props.index * 0.1 };
`;

With this component rendered over a collection of items, we'll generate a new style tag with an associated class for each one.

Is there a recommended way of working with these kinds of styles so as not to thrash the head with a new style tag everytime render is called on Comp?

  • One solution could be to move the /* lots of styles here */ into another component that doesn't include the dynamic properties that cause huge amounts of CSS to be rendered into the head. This way the generated style tag only contains the animation-delay property. Still a lot of style tags being injected into the head though and since the injection only happens at render time, this could cause some trashing.
  • Another option is to put the animationDelay into the style prop of the component as we compose the components and not let styled-components handle this.

How would you do this? Is there a recommended approach?

I saw there might be some plans to extract static styles which, as a solution, is similar to our first option above.

Activity

  1. JamieDixon commented on Oct 24, 2016

    @JamieDixon
    ContributorAuthor

    On the other hand, it could be that we're trying to do things with styled-components that it's just not designed for.

    Another option would be to use something like Velocity to handle our animations and styled-components for the rest.

  2. mxstbr commented on Oct 24, 2016

    @mxstbr
    Member

    Have you noticed any visible performance impact on the animation with the current way? If so, could you provide a reproduction in a webpack bin?

  3. mikepombal commented on Oct 24, 2016

    @mikepombal

    Hi @mxstbr,

    No performance impact but duplication of the same style again and again which increases the bundle size. Following @JamieDixon example if we have a list of Comp components the style created will be the following:

    .[generated class name for 1st instance of comp] {
        /*lots of styles here*/
        animation-delay: 0s;
    }
    .[generated class name for 2nd instance of comp] {
        /*lots of styles here*/
        animation-delay: 0.1s;
    }
    .[generated class name for 3rd instance of comp] {
        /*lots of styles here*/
        animation-delay: 0.2s;
    }
    /* and so on */

    As you see the /*lots of style here*/, although it is the same style, appears n times the number of items in the list.

    I'm wondering if #59 could actually fix this issue.

  4. vdanchenkov commented on Oct 25, 2016

    @vdanchenkov
    Member

    Comparison of animation done directly with style prop and with styled-components. http://www.webpackbin.com/VJ3-tBukf In this example animation with props is about 2 times slower on first run.

  5. added this to the milestone on Oct 30, 2016
  6. JamieDixon commented on Oct 31, 2016

    @JamieDixon
    ContributorAuthor

    I came across an example today where styled-components couldn't nicely handle the requirement I had.

    This is a colour picker that I'm currently building and the colour of the centre is equal to the chosen colour on the scale. Here's two gifs showing a smooth colour transition when using the style prop and a staggered colour transition with styled-components.

    I'm not sure what the answer is to this but wanted to provide it as an example of the aforementioned issue.

    style=
    smooth

    styled-components
    stutter

    where

    background: ${props => `rgb(${props.rgb})`};
    
  7. mxstbr commented on Oct 31, 2016

    @mxstbr
    Member

    I'm not sure what the answer is to this but wanted to provide it as an example of the aforementioned issue.

    Sorry, I'm not 100% sure what I should be looking at here! Is the staggering due to styled-components?

  8. JamieDixon commented on Oct 31, 2016

    @JamieDixon
    ContributorAuthor

    Yeah. The stagger is caused because styled-components needs to generate a new <style> tag in the head and switch out the class on the element every time the mouse moves.

    I suspect this is just a mis-use of styled-components.

  9. mxstbr commented on Oct 31, 2016

    @mxstbr
    Member

    Oh god, that's no good. I'll dig into this soon!

  10. geelen commented on Nov 2, 2016

    @geelen
    Member

    Took a look at this, it is working the way I expected, and yeah it's not ideal for cases like this. First up, the demo: https://styled-components-134.surge.sh/

    I'm using the following component (source here):

    const Box = styled.div`
      margin: 2rem auto;
      width: 360px;
      height: 360px;
      background: hsl(
        ${props => props.hue}, 
        ${props => 50 + props.luminosity / 2}%, 
        ${props => props.luminosity}%
      );
    `

    And it seems... about as fast as I expected. It is generating a new CSS classname for each colour value but they're all being injected into their own <style> tag:

    image

    Now, SC will use multiple <style> tags as the number of components grows for performance reasons (big <style> tags do slow down), but each component's styles are co-located because otherwise some 👻 spooky 👻 stuff happens (see #31, #1). That's also the reason we re-generate all the CSS for the component rather than a "static" chunk and a "dynamic" chunk. So there's not any great bug we can squash to make this perform better, sadly.

    The solution is, of course, to use inline styles for anything that's going to change really often. For one, these don't require parsing & serialising CSS in JS, but also they don't invalidate anything the browser has already understood about the CSS. They're basically the "right tool for the job"

    We could, however, expose inline styling through an API, something like this:

    const Box = styled.div`
      margin: 2rem auto;
      width: 360px;
      height: 360px;
      :inline {
        background: hsl(
          ${props => props.hue}, 
          ${props => 50 + props.luminosity / 2}%, 
          ${props => props.luminosity}%
        );
      }
    `

    Or something to that effect. Anyway, for now, just use the style attribute like normal. It'll be passed through and you'll be a-ok 👍

  11. kof commented on Nov 9, 2016

    @kof

    I think this case should be avoided completely. Ideally user would be allowed to declare styled components only in the top level scope of the module, same like import statement. Otherwise this is going to be misused for stuff like animations which require super high performance, and won't go well with this rendering.

  12. mxstbr commented on Nov 10, 2016

    @mxstbr
    Member

    Ideally user would be allowed to declare styled components only in the top level scope of the module, same like import statement.

    How does that solve the problem, this component still has this issue even when declared at the top level scope:

    import styled from 'styled-components';
    
    // Top level
    const Box = styled.div`
      margin: 2rem auto;
      width: 360px;
      height: 360px;
      background: hsl(
        ${props => props.hue}, 
        ${props => 50 + props.luminosity / 2}%, 
        ${props => props.luminosity}%
      );
    `
  13. kof commented on Nov 10, 2016

    @kof

    Oh I thought the issue comes from creating the styled component within render, but its only part of the problem. In this example its the functions which can accept props...

    What is the current rendering behavior, when a styled component becomes new props and returns a different style, what do you do?

  14. mxstbr commented on Nov 10, 2016

    @mxstbr
    Member

    Inject a new style fragment, since it might only apply to a single instance of the component, not generally!

  15. 20 remaining items

  16. jacobp100 commented on Feb 23, 2017

    @jacobp100
    Contributor

    Just a thought on putting all dynamic styles inline. It's obviously a breaking change, since it'll alter the specificity. Also, a lot of people seem to be using the theming aspect of styled-components, which would cause everything to be inlined.

    But we could provide it as an option. If we did, we could extract all the non-dynamic CSS into a static CSS file via a babel-plugin.

    Other than that, css-variables and the style prop seem to be the way to get it to work as of current.

  17. k15a commented on Feb 23, 2017

    @k15a
    Member

    @jacobp100 The problem with inlining dynamic styles is that you can write dynamic styles in :hover or @media and you can't inline those.

  18. jacobp100 commented on Feb 23, 2017

    @jacobp100
    Contributor

    It would definitely have to be an opt-in thing. You could generate some css custom properties and inject those into the inline styles to get it to work in :hover etc. I suppose this is v2 and beyond though!

  19. mxstbr commented on Jul 1, 2017

    @mxstbr
    Member

    I'll finally close this discussion since a lot of things have changed since the initial kickoff by @JamieDixon. (thanks!)

    1. We've added a warning when you change styles too often that logs to the console and suggests using inline styles for highly dynamic styles to avoid this kind of confusion.
    2. We now have the .attrs selector, making dynamic styles that come in via props possible with inline styles. You could change the bg prop of this component a lot of times without running into performance issues. (I'd be interested to see the color picker from above reworked this way though!)
    const HighlyDynamicComponent = styled.div.attrs({
      style: props => ({
        background: props.bg,
      })
    })`
      color: blue;
    `
    1. More future-wise we're focusing on performance at the moment, @geelen has found a way to batch style injection that'll come out with the next patch release which will speed up initial and rerenders by orders of magnitude. We'll finally be in a similar spot to all other CSS in JS libraries, which means many more dynamic use cases will now be possible too!

    That should clear up most, if not all concerns around highly dynamic styles and styled-components. If you have further issues, suggestions or comments please feel free to open a new issue with your ideas!

  20. JamieDixon commented on Jul 1, 2017

    @JamieDixon
    ContributorAuthor

    👍 thanks for all you've done @mxstbr. I might have a shot at the colour picker this weekend!

  21. mxstbr commented on Jul 1, 2017

    @mxstbr
    Member

    That'd be awesome, let me know when it's done!

  22. JamieDixon commented on Sep 10, 2017

    @JamieDixon
    ContributorAuthor

    @mxstbr Better late than never!

    It works beautifully. Thanks for the great work everyone. SC has made such a difference to our project.

    sep-10-2017 11-52-05

  23. melMass commented on Jan 27, 2019

    @melMass

    @mxstbr Can you please guide me to the doc related to attrs?
    I don't get the syntax needed for string expansion:

    Here is my div:

    const BG = styled.div.attrs(
        ( { x, y } ) => ( { 
            bgcolor: `rgba(${ x * 3.6 },${ y * 3.6 },0,1)`
    } ) )`
      background-color:${ props => props.bgcolor };
    `

    Edit:
    Ok I got the idea behind attrs here is the working version:

    const BG = styled.div.attrs({
      style: props => ({ 
        backgroundColor: `rgba(${ props.x * 3.6 },${ props.y * 3.6 },0,1)` }) 
    })`
      pointer-events:none;
    `
  24. melMass commented on Jan 27, 2019

    @melMass

    Forget it...

    I just understood the use of attrs (mix of props and html attributes) !!! It's useful for many other stuff aswell, glad to discover that one.

    It should be more obvious in the docs and it needs more use cases examples (I can already think of many) IMHO!
    Thanks

  25. philtrem commented on May 3, 2019

    @philtrem

    Yeah. The stagger is caused because styled-components needs to generate a new <style> tag in the head and switch out the class on the element every time the mouse moves.

    I suspect this is just a mis-use of styled-components.

    I ran into the same problem.

    here's a video (although there isn't a noticeable slowdown in that demo, but it does get slow over time): https://www.youtube.com/watch?v=D1pgPdU3D8M

  26. jtomaszewski commented on Jun 3, 2019

    @jtomaszewski

    @mxstbr Maybe we should add a note to documentation somewhere on styled components page, that this .attrs() method should be used instead of inlining dynamically-and-often-changed variables into the css? (Current documentation mentions other reasons when attrs should be used or not used, but not the performance reason.)

    P.S. Is there a "Best performance practices" article somewhere on styled-components page?

  27. coreybruyere commented on Jan 23, 2020

    @coreybruyere

    ☝️ Any section for styled-components best practices? I too, was unaware of the attrs perf hack.

  28. bartzy commented on Jul 12, 2020

    @bartzy
    1. More future-wise we're focusing on performance at the moment, @geelen has found a way to batch style injection that'll come out with the next patch release which will speed up initial and rerenders by orders of magnitude. We'll finally be in a similar spot to all other CSS in JS libraries, which means many more dynamic use cases will now be possible too!

    @mxstbr Can you perhaps comment if the issue(s) in this thread are a concern with v5? For styles that change a lot, should one still use the attrs solution your proposed?

    Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions