Skip to content

Understanding @emotion/babel-plugin's cssPropOptimization #2743

@CodeWitchBella

Description

@CodeWitchBella

Description:

I was trying to understand how to best take advantage of @emotion/babel-plugin's css prop optimization, how it works etc.

I create a simple playground on codesandbox (source) and discovered the following:

If you use css prop in its most simple form with object-style syntax you get a hoisted object (playground link)

function Test() {
  return <div css={{ color: 'blue' }} />
}
// Turns into (with dev-only code stripped for brevity)
var _ref = {
  name: "117wnve",
  styles: "color:blue"
};

function Test() {
  return <div css={_ref} />;
}

It gets more complicated if you pass (possibly) dynamic values (playground link)

function Test() {
  const background = 'white'
  return <div css={{ color: 'blue', background }} />
}
// turns into
import { css as _css } from "@emotion/react";

function Test() {
  const background = 'white';
  return <div css={/*#__PURE__*/_css({
    color: 'blue',
    background
  })} />;
}

and (playground link)

function Test() {
  const background = 'white'
  return <div css={[{ color: 'blue' }, {background}]} />
}
// turns into
function Test() {
  const background = 'white';
  return <div css={["color:blue;", {
    background
  }]} />;
}

My question is: which is better to use? Let's say this is in often-used component (like Button) and the static object contains many properties but we have a few dynamic ones (eg. color, borderColor and background from theme provided by react context). Is it better to split static values and dynamic values into separate objects so that static ones become strings, or should we keep that as one object and rely on _css function?

My gut feeling would be to split it, but I would want to measure that before jumping to conclusions and I figured I would ask first before doing that :-)

Also, if there is a noticeable difference would it make sense for the babel plugin to transform from one to the other automatically?

Thank you for awesome library

Documentation links:

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions