Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Styled Component's CSS method optimization

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};
    `;
  }}
`;
like image 212
Victor Le Avatar asked May 31 '26 01:05

Victor Le


1 Answers

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};
`);
like image 155
Raicuparta Avatar answered Jun 01 '26 22:06

Raicuparta