3

Which is more optimized and why?

I hear that the css method from Styled-component is pretty expensive but I'm wondering if the multiple nested ${(prop) => {}} is more expensive than the single fn with the css method used inside.

Approach 1

const Foo = styled.div`
  border-radius: 50%;
  display: flex;
  width: ${(props) => props.size};
  height: ${(props) => props.size};
  color: ${(props) => props.bgColor};
  background-color: ${(props) => props.bgColor};
`;

vs

Approach 2

const Bar = styled.div`
  border-radius: 50%;
  display: flex;
  ${(props) => {
    return css`
      width: ${props.size};
      height: ${props.size};
      color: ${props.bgColor};
      background-color: ${props.bgColor};
    `;
  }}
`;

1 Answer 1

3

Performance difference should be negligible. The only optimization Styled Components would make is if your styles were static (with no interpolations).

Note that styled.div or any other of the Styled CSS methods already do the same work as css. And these methods accept functions as arguments (instead of interpolated strings). So you can take it a step further and do this:

const Baz = styled.div((props) => css`
  border-radius: 50%;
  display: flex;
  width: ${props.size};
  height: ${props.size};
  color: ${props.bgColor};
  background-color: ${props.bgColor};
`);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.