Search code examples
reactjsstyled-components

What is different styled(component) and styled(tagname) in performance issues of react?


I'm new to styled-components and I was wondering what is different styled(component) and styled(tagname) in performance issues of react.

styled(tagname)

const StyledP = styled('p')``

export const StyledComponent = props => (
  <StyledP>{props.name}</StyledP>
)

enter image description here

enter image description here

styled(component)

const FunctionalComponent = props => (
  <p className={props.className}>{props.name}</p>
)

export const StyledComponent = styled(FunctionalComponent)`
`

enter image description here enter image description here

I looked at the this comment and found out if I using styled(component). but I don't know in performance issues of react. can someone please explain?


Solution

  • Its the same API with a few additional checks in case the target is a component. Extracted from the styled constructor source code :

    const isTargetStyledComp = isStyledComponent(target);
    
    // fold the underlying StyledComponent attrs up (implicit extend)
    const finalAttrs =
      // $FlowFixMe
      isTargetStyledComp && target.attrs
        ? Array.prototype.concat(target.attrs, attrs).filter(Boolean)
        : attrs;
    
    // fold the underlying StyledComponent rules up (implicit extend)
    const componentStyle = new ComponentStyle(
      isTargetStyledComp ? target.componentStyle.rules.concat(rules) : rules,
      finalAttrs,
      styledComponentId
    );
    
    // $FlowFixMe
    WrappedStyledComponent.foldedComponentIds = isTargetStyledComp
      ? // $FlowFixMe
        Array.prototype.concat(target.foldedComponentIds, target.styledComponentId)
      : EMPTY_ARRAY;
    
    WrappedStyledComponent.target = isTargetStyledComp ? target.target : target;
    

    To summarize:

    • Extend the attrs and rules of the base styled component with the derived styled component's rules.
    • Keep a list of componentIds, in case of nested styled(Component) extensions.
    • Preserve the original target element (dom string), as the target for all extensions.