Skip to Content
vitus·labs
Styler

Styler

CSS-in-JS engine for Vitus Labs UI System — ~7.0 KB min+gz, React 19 SSR via <style precedence>, regression-gated competitive bench.

@vitus-labs/styler is a CSS-in-JS engine with a styled-components-compatible API: tagged template literals, styled.tag shorthand, as polymorphism, $-prefixed transient props, refs, theming, keyframes, createGlobalStyle, component selectors, styled(StyledComponent) extension, and SSR. The engine has a static/dynamic split with multi-tier caching and uses React 19's <style precedence> for SSR streaming.

Installation

npm install @vitus-labs/styler

Peer dependencies: react >= 19, react-dom >= 19

Key Features

  • ~7.0 KB min+gz (React external; ~18.9 KB minified) — full SSR engine with @layer, at-rule splitting, and concurrent-mode-safe injection.
  • Static/dynamic split — templates with no function interpolations compute their class name once at module load; subsequent renders return a pre-built ReactElement with no resolve / hash / createElement work.
  • FNV-1a hashing — deterministic class names (vl-<base36>), automatic dedup. Hash loop is 4-char-unrolled for ~+15-46% throughput vs the per-char loop.
  • CSS-in-CSS composition — nest css`…` results inside styled`…` or other css`…` . Static nested results are memoized per-instance (one resolve, reused across every consumer's render).
  • React 19 SSR — <style precedence="medium"> on server (referenced @keyframes ride along), useInsertionEffect into a single shared <style data-vl> element on client. No manual collectStyles / ServerStyleSheet boilerplate.
  • Component selectors — interpolate a static styled component (${Button}:hover &) to target its class.
  • Extension folding — styled(StyledComponent) folds base + extension into one component; the extension wins.
  • Transient props — $-prefixed props consumed by styles but never forwarded to DOM.
  • Polymorphic as prop — render as any element or component; ref is a regular prop (React 19), so it reaches whatever is rendered.
  • Specificity boost — boost: true doubles the selector to (0,2,0) for library-component overrides.
  • @layer support — opt in via createSheet({ layer: 'components' }).
  • Bounded lookup caches — maxCacheSize (default 10,000) with 10% oldest-first eviction of the cssText lookup caches. Rules already in the DOM are never evicted.
  • Every tag works — styled.div, styled.p, styled.section, styled('my-element') all hit the same Proxy handler. Zero bytes per tag added to the bundle.
  • CI-gated perf — every PR runs the bench workflow which fails on >10% regression vs main on the same runner.

What's new in 2.9

2.9 is a minor release for styler — check the migration notes

Two changes can alter existing output, which is why @vitus-labs/styler got a minor bump:

  1. styled(StyledComponent) now folds into one component. The base template is followed by the extension in a single rule, so the extension's declarations deterministically win. If an extension relied on the base winning a specificity tie, move that declaration into the extension (or drop it from the extension).
  2. The injected context theme is no longer forwarded to custom component targets by dynamic styled components (this matches the static path). A wrapped component that read props.theme should call useTheme() instead. An explicitly passed theme prop is still forwarded.

2.9.0

  • styled(StyledComponent) folding — styled-components v6 semantics: one component, one rule (base first, extension after), $-transient props reach the base's interpolations, and ${Base} selectors still match extensions. styled(NonStyledComponent) and wrappers that hoist statics (e.g. attrs / rocketstyle components) are unchanged. See Extending Styled Components.
  • createGlobalStyle is mount-scoped and ref-counted — rules are inserted when the first instance mounts and removed when the last one unmounts; a dynamic global that changes value (A → B → A) replaces its previous rules instead of leaving stale ones in effect.
  • SSR / hydration fixes — @keyframes referenced by a component or global style are shipped inside its <style precedence> tag (they were missing from SSR HTML); hydration reads every token of a merged data-href="vl-a vl-b" tag, so SSR rules are no longer duplicated on the client; useCSS no longer grows a shared server buffer (it emits no CSS on the server).
  • Cache eviction — maxCacheSize now only trims the cssText lookup caches; the set of rules already in the DOM is never evicted (evicting it re-inserted live rules, duplicating them and reordering the cascade).

2.8.0

  • Component selectors — ${Button} { … } resolves to the class of a static styled component; using a dynamic one throws a clear error. See Component Selectors.
  • Function themes — <ThemeProvider theme={(outer) => ({ ...outer, x })}>. See Theming.
  • Prop forwarding — styled.svg keeps SVG attributes (viewBox, d, fill, stroke*, …), every on[A-Z]* handler is forwarded when it is a function, inert / popover* / suppressHydrationWarning are allowed, and a custom shouldForwardProp is honoured for component targets too.
  • Global CSS — @import / @charset are inserted first and no longer break insertRule; boosted and unboosted identical CSS get distinct class names.
  • Dynamic styled components without a ThemeProvider pass an empty theme object to interpolations (never undefined), and don't forward it to wrapped components.

Try It Live

css()

Tagged template for composable CSS fragments. Returns a lazy CSSResult object — no CSS resolution happens at creation time.

import { css } from '@vitus-labs/styler'

// Static — stored as-is, resolved when consumed
const highlight = css`
  color: red;
  font-weight: bold;
`

// Dynamic — function interpolations resolved at render time with props + theme
const dynamic = css`
  color: ${(props) => props.$color || 'blue'};
  padding: ${(props) => props.$size}px;
`

// Composition — nest css results inside other css
const combined = css`
  ${highlight}
  border: 1px solid gray;
`

// Array interpolation — flattened automatically
const responsive = css`
  ${[
    css`color: red;`,
    css`margin: 0;`,
  ]}
`
// Resolves to: "color: red;margin: 0;"

CSSResult

css() returns a CSSResult instance that stores the raw template strings and interpolation values:

class CSSResult {
  readonly strings: TemplateStringsArray
  readonly values: Interpolation[]

  // Resolve with empty props (useful for testing/debugging)
  toString(): string
}
  • No computation at creation time — only stores references
  • Resolved when consumed by styled, useCSS, or toString()
  • Instance check: value instanceof CSSResult detects nested CSS for composition
  • Pre-init css from @vitus-labs/core: config.css called before init() returns a thunk; styler unwraps it when the template is created, so a static template built before init() stays static

Interpolation Types

TypeBehavior
string / numberInserted directly into CSS
CSSResult (from another css call)Recursively resolved and flattened
Interpolation[] (array)Each element resolved and concatenated
(props) => InterpolationCalled at render time with { ...componentProps, theme }
Static styled component (${Button})Replaced with its class selector (.vl-<hash>) at creation — see Component Selectors
true / falseConverted to empty string (enables ${condition && css\...`}`)
null / undefinedConverted to empty string
type Interpolation =
  | string
  | number
  | boolean
  | null
  | undefined
  | CSSResult
  | CSSEngineResult   // from @vitus-labs/core (e.g. unistyle's styles())
  | Interpolation[]   // recursive
  | ((props: { theme?: DefaultTheme; [key: string]: any }) => Interpolation)

CSS Normalization

Resolved CSS goes through a single-pass normalization that:

  • Strips /* block comments */ and // line comments (quoted strings and url(...) contents — e.g. url(//cdn…), content: "//" — are preserved verbatim)
  • Collapses whitespace to single spaces
  • Removes redundant semicolons (after {, }, other ;)

styled()

Component factory that creates styled React components with automatic class name management, ref forwarding, and prop filtering.

import { styled } from '@vitus-labs/styler'

// Tag shorthand via Proxy
const Box = styled.div`
  padding: 16px;
  border-radius: 8px;
`

// Direct call syntax
const Card = styled('section')`
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
`

// Wrap an existing (non-styled) component — it receives `className`
const StyledButton = styled(MyButton)`
  cursor: pointer;
`

// With options
const Custom = styled('div', {
  shouldForwardProp: (prop) => !prop.startsWith('custom'),
  boost: true,
})`
  padding: 16px;
`

Options

styled(tag: string | ComponentType, options?: StyledOptions)
OptionTypeDefaultDescription
shouldForwardProp(prop: string) => boolean—Control which props reach the DOM element
boostbooleanfalseDouble the selector (.vl-abc.vl-abc) for specificity (0,2,0)

Dynamic Props & Transient Props

Props prefixed with $ are automatically filtered from DOM output:

const Button = styled.button`
  background: ${(props) => props.$variant === 'primary' ? '#0d6efd' : '#6c757d'};
  color: white;
  padding: ${(props) => props.$size === 'large' ? '12px 24px' : '8px 16px'};
`

<Button $variant="primary" $size="large">Click me</Button>
// Renders: <button class="vl-abc123">Click me</button>
// $variant and $size consumed by styles, NOT forwarded to <button>

Polymorphic as Prop

Override the rendered element type at the call site:

const Box = styled.div`
  padding: 16px;
`

<Box as="section" />      // renders <section>
<Box as="article" />      // renders <article>
<Box as={MyComponent} />  // renders <MyComponent>

The as prop works in both static and dynamic paths and is never forwarded to the underlying element.

Refs

Styled components take ref as a regular prop (React 19 — no forwardRef wrapper) and pass it to the rendered element or component:

const Input = styled.input`
  border: 1px solid gray;
`

const ref = useRef<HTMLInputElement>(null)
<Input ref={ref} />  // ref points to the <input> DOM element

shouldForwardProp

For custom prop filtering logic:

const Input = styled('input', {
  shouldForwardProp: (prop) => prop !== 'hasError',
})`
  border-color: ${(props) => props.hasError ? 'red' : 'gray'};
`

<Input hasError />
// hasError used by styles but NOT forwarded to <input>

shouldForwardProp applies to both DOM tags and wrapped components. With a custom filter on a DOM tag, the filter alone decides (it replaces the default HTML filter below).

Without a custom filter, a wrapped component receives every prop except as, $-prefixed transient props and the context theme the engine injects (an explicitly passed theme prop is forwarded). Use useTheme() inside the wrapped component to read the theme.

Default Prop Filtering

For DOM elements without custom shouldForwardProp:

Prop PatternForwarded?
$-prefixed (e.g., $color)No — transient props
asNo — consumed for polymorphism
themeNo
data-*Yes
aria-*Yes
Known HTML and SVG attributes (viewBox, d, fill, stroke*, …, plus inert, popover*, suppressHydrationWarning)Yes
on[A-Z]* event handlers (incl. *Capture, media, pointer, toggle)Yes — only when the value is a function
Unknown propsNo — prevents React warnings

Class Name Merging

User-provided className is merged with the generated class:

<Box className="extra">Hello</Box>
// Renders: <div class="vl-abc123 extra">Hello</div>

Specificity Boost

Double the selector to raise specificity from (0,1,0) to (0,2,0):

const Override = styled('div', { boost: true })`
  color: red;
`
// Generates: .vl-abc.vl-abc { color: red; }
// Overrides inner library components regardless of CSS source order

Boosted and unboosted copies of identical CSS get distinct class names, so both rules are inserted.

Component Selectors

Interpolate a static styled component (no function interpolations) to use its generated class as a selector — in styled, css or createGlobalStyle:

const Icon = styled.svg`
  width: 16px;
  transition: transform 0.2s;
`

const Button = styled.button`
  display: inline-flex;
  gap: 8px;

  &:hover ${Icon} {
    transform: translateX(2px);
  }
`
// ${Icon} resolves to `.vl-<hash>` of Icon's class

A dynamic styled component has no stable class, so using it as a selector throws [styler] styled(…) cannot be a selector (needs a static template) at creation time. Selectors keep working through extension: an element rendered by an extension of Icon still carries Icon's class.

Extending Styled Components

Passing a styled component to styled() folds both templates into one component (styled-components v6 semantics) instead of nesting two:

const Button = styled.button`
  padding: 8px 16px;
  color: ${(p) => (p.$danger ? 'crimson' : 'inherit')};
`

const PrimaryButton = styled(Button)`
  background: #0d6efd;
  color: white;
`
  • The base template is followed by the extension in a single rule, so the extension's declarations deterministically win (color: white above).
  • $-transient props reach the base's interpolations.
  • shouldForwardProp / boost options compose: the extension's filter runs first, then the base's (or the default HTML filter for a DOM tag).
  • ${Button} selectors still match elements rendered by PrimaryButton.

Wrapping a non-styled component — including components from @vitus-labs/attrs / @vitus-labs/rocketstyle that hoist styled statics — still creates a wrapper that passes className down.

Migrating to 2.9

Before 2.9 the extension was a separate component with its own rule, so the cascade could let the base win a specificity tie. If you relied on that, move the declaration into the extension.

Static vs Dynamic Paths

The engine automatically detects whether a template has dynamic interpolations and uses the optimal path:

Static Path

When no interpolation values are functions (or nested CSSResults containing functions):

  1. CSS resolved once at component creation time (module evaluation)
  2. Class name computed and CSS injected immediately
  3. Zero per-render overhead — no theme context access, no resolution
  4. Component simply applies the pre-computed class name
// Static — class computed once, shared across all instances
const Box = styled.div`
  padding: 16px;
  margin: 8px;
  background: white;
`

Dynamic Path

When any interpolation is a function:

  1. Theme accessed via useTheme() on every render (an empty {} without a ThemeProvider)
  2. CSS resolved with { ...componentProps, theme } — the injected theme is never forwarded to the rendered element or wrapped component
  3. useRef cache — CSS string comparison avoids rehashing when content unchanged
  4. useInsertionEffect injects CSS synchronously before paint
  5. Dedup cache prevents duplicate style injection
// Dynamic — resolved per render, cached by CSS string comparison
const Box = styled.div`
  padding: ${(props) => props.$p}px;
  color: ${(props) => props.theme.colors.primary};
`

keyframes()

Create CSS @keyframes animations. Injection is synchronous and immediate.

import { keyframes, styled } from '@vitus-labs/styler'

const fadeIn = keyframes`
  from { opacity: 0; transform: translateY(-10px); }
  to { opacity: 1; transform: translateY(0); }
`

const FadeInBox = styled.div`
  animation: ${fadeIn} 0.3s ease-in-out;
`

Behavior

  • Returns a KeyframesResult with a .name property (vl-kf-<hash>)
  • String coercion returns the animation name for use in CSS interpolations
  • Deterministic naming via FNV-1a hash of the CSS body
  • No dynamic interpolations — keyframes are always static
  • Injected as @keyframes vl-kf-<hash> { ... } into the global sheet
  • Deduplicated by animation name
  • SSR: the @keyframes rule is shipped inside the <style precedence> tag of every component or global style that references it, so animations work in server-rendered HTML

createGlobalStyle()

Inject unscoped global CSS. Returns a React component.

import { createGlobalStyle } from '@vitus-labs/styler'

const GlobalStyles = createGlobalStyle`
  * {
    box-sizing: border-box;
    margin: 0;
  }

  body {
    font-family: system-ui, sans-serif;
    background: ${(props) => props.theme?.background || '#fff'};
  }
`

function App() {
  return (
    <>
      <GlobalStyles />
      <Main />
    </>
  )
}

Behavior

  • Returns a React component (not a CSSResult); it renders nothing on the client
  • Component props are merged with theme for interpolation resolution
  • Unscoped — CSS injected without any .vl-* class wrapper
  • Mount-scoped and ref-counted — rules are inserted (via useInsertionEffect) when the first instance mounts and removed when the last instance unmounts, like styled-components
  • Static path: CSS resolved once at creation
  • Dynamic path: CSS resolved per render; when the value changes (A → B → A) the previous rules are released and replaced, never left in effect
  • @import / @charset rules are inserted at the top of the sheet
  • SSR: Renders <style precedence="low"> — lower precedence than component styles (medium) — including any referenced @keyframes. Rules hydrated from SSR are kept on unmount
  • Deduplicated by hash of resolved CSS

useCSS()

Hook that resolves a CSSResult to a class name string. Use when you need styling without creating a styled component wrapper.

import { css, useCSS } from '@vitus-labs/styler'

const highlight = css`
  color: red;
  font-weight: bold;
`

function Label({ children }) {
  const className = useCSS(highlight)
  return <span className={className}>{children}</span>
}

Signature

useCSS(
  template: CSSResult,
  props?: Record<string, any>,
  boost?: boolean
): string  // class name

Dynamic Styles

const badge = css`
  background: ${(props) => props.variant === 'success' ? 'green' : 'gray'};
  padding: 4px 8px;
  border-radius: 4px;
`

function Badge({ variant, children }) {
  const className = useCSS(badge, { variant })
  return <span className={className}>{children}</span>
}

Theme is automatically merged from context. Same caching and injection mechanism as styled() on the client.

SSR

useCSS only returns a class name, so there is no element to carry a <style precedence> tag. On the server it returns the (deterministic) class name but emits no CSS — the rules are injected when the client hydrates. Use styled() for markup that must be styled in the server HTML.

CSS Nesting

Native CSS nesting with & selectors is fully supported:

const Card = styled.div`
  background: white;
  padding: 16px;

  & h2 {
    margin-bottom: 8px;
    font-size: 1.5rem;
  }

  & p {
    color: #666;
  }

  &:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }

  &.active {
    border-color: blue;
  }
`

At-Rule Splitting

@media, @supports, and @container at-rules are automatically extracted from the CSS body and emitted as separate top-level rules with the selector wrapped inside. This works around CSSOM spec limitations:

const Responsive = styled.div`
  font-size: 14px;
  @media (min-width: 600px) {
    font-size: 18px;
  }
`
// Emits two rules:
// .vl-abc { font-size: 14px; }
// @media (min-width: 600px) { .vl-abc { font-size: 18px; } }

Non-splittable at-rules (@keyframes, @font-face) are left in place.

Deduplication & Caching

  • Same CSS always produces the same FNV-1a hash → same class name
  • If two components generate identical CSS, the rule is injected once and both share the class name
  • Dynamic path uses a useRef cache per component instance — string comparison skips rehashing when CSS unchanged between renders
  • The cssText lookup caches (insertCache, prepareCache) are bounded by maxCacheSize (default 10,000) and the normalizeCSS cache by 2,000 entries; each evicts its oldest 10% on overflow
  • The set of rules already in the DOM is never evicted — evicting it would re-insert live rules (duplicates + cascade reorder)

HMR Support

For development with hot module replacement:

import { sheet } from '@vitus-labs/styler'

if (import.meta.hot) {
  import.meta.hot.accept(() => {
    sheet.clearAll()  // Purge all cached + injected styles
  })
}
  • sheet.clearCache() — Clears the dedup cache plus the resolve-side caches (insertCache, prepareCache, normCache). Keeps the already-injected CSS in the DOM. Useful for HMR scenarios where you want to recompute classes but not flush rules.
  • sheet.clearAll() — Clears everything clearCache() does, plus the SSR buffer, plus removes all rules from the DOM. Also fires registered clearCallbacks so consumers like styled.ts reset their staticComponentCache and hotCache. Use for full HMR resets.

Benchmarks

Bundle size

Fresh build of @vitus-labs/styler (rolldown, ESM, react externalized):

BuildSize
Minified18.94 KB
Minified + gzipped~7.0 KB (6.98 KB)

Competitor numbers below are from each library's published artifact (read off bundlephobia / their dist files); they're a snapshot, not a regression-gated measurement:

LibraryGzipped
goober~1.3 KB
@vitus-labs/styler~7.0 KB
@emotion/react + styled~16.6 KB
styled-components 6~17.9 KB

If you need the smallest possible bundle and don't need SSR or full HTML-prop filtering, goober is the minimal option. styler's positioning is "full SSR + composition + dedup + caching in about 7 KB min+gz."

What drives the size

ModuleWhat it ships
sheet.tsStyleSheet class, SSR hydration, @media/@supports/@container rule splitting, @layer wrapping, bounded cache + eviction, prepare() cache for <style precedence>, onClear broadcast hooks
styled.tsstatic/dynamic split, styled(StyledComp) folding, component-selector metadata, hot + WeakMap component cache, LRU-2 cssText cache per dynamic render, polymorphic as prop, SSR vs client branches
forward.tsHTML attribute allowlist, transient ($-prefix) prop filter, shouldForwardProp option
resolve.tstagged-template resolver, normalizeCSS single-pass scanner, _isDynamic / _staticResolved per-instance caches
globalStyle.tscreateGlobalStyle (static + dynamic paths, mount-scoped ref-counting, SSR precedence)
Otherhash (4-char-unrolled FNV-1a), useCSS, keyframes, ThemeProvider, evict, css, shared, index

Competitive bench (render-to-string + CSR)

The canonical regression-gated suite is in-repo at packages/styler/benchmarks/css-perf.bench.tsx. Run with bun run bench from the styler package. Same-process tinybench, equivalent work (styled-components is wrapped in ServerStyleSheet so all three libraries serialize CSS on the SSR rows). Numbers below are from the package README (bun 1.3.14 / react 19.2.6, jsdom).

Scenariostyler ops/semotion ops/ssc 6 ops/sstyler vs best competitor
SSR static (500 renders/tick)687.9323.2203.02.13× vs emotion
SSR dynamic (500 renders/tick)426.2306.9198.21.39× vs emotion
SSR themed (500 renders/tick)348.9247.2161.71.41× vs emotion
CSR mount (100 mounts/tick)14,33614,06914,281+0.4% vs sc (tie)
CSR update (100 updates/tick)13,54713,38813,403+1% vs sc (tie)
CSR many (50 distinct comps/tick)19,61118,3385,788+7% vs emotion (3.39× vs sc)

The SSR gap is where styler's React 19 <style precedence> + static-element cache pay off — both emotion and styled-components have to serialize via heavier paths (sc explicitly via ServerStyleSheet, emotion via its own SSR plumbing). The CSR mount/update numbers are within ~2% across all three libraries because React's reconciler dominates the per-render cost.

A >10% regression on any styler row vs main on the same runner fails the bench workflow. This caught a real regression during the 2.6.x perf round and forced a revert before merge.

Helper-level microbench (audit history)

A second bench at packages/styler/benchmarks/perf-audit-bench.tsx compares individual helper old-vs-new in the same process. This is the bench used to verify each perf-PR's claimed delta during audit; representative recent results (median of 3 runs):

HelperΔ vs main-before-PR
CSSResult._staticResolved cache (nested-static, 8 repeats)+149%
hashUpdate 4-char unroll (337-char CSS)+46%
hashUpdate 4-char unroll (25-char CSS)+15%
HTML_PROPS Set → null-proto key in obj (5-lookup mix)+19%

These translate into ~0% headline bench movement (the helpers target paths the headline bench doesn't exercise — nested static composition, very long CSS strings, deep buildProps calls). They land for real-app workloads with shared css\…`` snippets, long stylesheets, and prop-heavy components.

Edit on GitHub

Last updated on

On this page