styled-components
styled-components copied to clipboard
A mechanism to use css variable
This PR related to Support CSS Varaible cause:
- prevent any recalculation(branching) by
styled-componentsfor dynamic value - generates just 1 style rule by relying on CSS variables as a tool to ship value from the component to the rule
- there is no breaking change
How can we use it?
To identify which prop is used for CSS variable purposes we can use $$ prefix, but it is not required.
const Comp = styled.div<{ $$fontSize?: string }>`
font-size: ${{ var: 'fontSize', compute: props => props.$$fontSize || "1rm" }};
`;
Usage:
<Comp $$fontSize="2rm" />
Then our component will be something like this:
<div className="sc-a b" style={{ "--fontSize": "2rm" }} />,
and it just generates a style rule even if we pass any dynamic values:
.b {
font-size: var(--fontSize);
}
That's mean if I pass a new value:
<div className="sc-a b" style={{ "--fontSize": "50px" }} />,
It can still rely on the previous style rule and it doesn't need to create a new style rule branch
Without this PR
Without this PR if we want to do something like the above example we should move logic inside the style to the component:
Style:
const Comp = styled.div<{ $$fontSize?: string }>`
font-size: var(--fontSize);
`;
Component:
<Comp style={{ '--fontSize': props.fontSize || "1rm" }} />
Despite it using CSS variables, it creates a style rule branch per any new value for --fontSize
I wonder if synthesizing css variables dynamically to avoid re-injecting styles would have some perf wins… like making it more automatic than this method so you don’t have to manually define anything. 🤔
At the moment, interpolations in styles lead to style branching which injects a lot of extra CSS. Leveraging variables in common scenarios that don’t require branching (like just updating a primitive value) could drastically trim down generated CSS for many projects.
You don’t have to manually define anything.
Then we have to move logics from separated styles file to component file:
Like this:
const Comp = styled.div`
font-size: var(--fontSize);
`;
<Comp style={{'--fontSize': props.fontSize || "1rm" }} />
Interpolations in styles lead to style branching which injects a lot of extra CSS
Exactly, but this PR can prevent any branching cause it relays on CSS variables and does not generate any other branch for dynamic values. please check this section:
https://github.com/styled-components/styled-components/blob/7f00c7fbaf04e1563021a6e0751c8e082b39d453/packages/styled-components/src/models/StyledComponent.ts#L160