简体   繁体   中英

Can I use Styled Components css`` method inside render function?

I know it is not recommended to define styled components inside the render function (or inside stateless function components) because of the performance issues. However, I wonder if using the css method in a render function will also affect the performance negatively?

function Component = ({children, ...props) => (
    <div css={`margin-bottom: 1rem`}>{children}</div>
);

Thanks!

After some testing, it appears that the css prop is similar to creating a memoized styled.element component. Component re-renders don't recreate the class name and state/prop manipulations act exactly same as a standard styled component -- when CSS properties have been altered, it either generates a new class or reuses an old one depending on how the CSS was changed. That said, the major downside to this approach would be that it requires babel-plugin-styled-components or babel-plugins-macro plus styled-components/macro to be added to your dependencies (if using styled-components/macro , it has to be imported into EACH file ) which may or may impact application compilation times and make your application larger.

So, if you're OK with the above, then you shouldn't notice too much/any application performance difference. But, is it really worth the extra dependency/dependencies plus additional babel configuration to save yourself from doing this:

import styled from "styled-components";

export default styled.div`
  margin-bottom: 1rem;
`;

which achieves the same result as above, but with less dependencies/less configuration/less effort. I don't know, that's up to you...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM