API Reference
Complete API reference for @vitus-labs/styler.
Exports
Everything exported from the package entry (@vitus-labs/styler has a single . export — there are no subpath imports):
import {
css,
styled,
keyframes,
createGlobalStyle,
ThemeProvider,
useTheme,
useCSS,
sheet,
createSheet,
} from '@vitus-labs/styler'
import type {
CSSResult,
Interpolation,
StyledOptions,
StyleSheetOptions,
DefaultTheme,
} from '@vitus-labs/styler'Styling Functions
css
css(strings: TemplateStringsArray, ...values: Interpolation[]): CSSResultTagged template for composable CSS fragments. Returns a lazy CSSResult that resolves when consumed by styled, useCSS, or toString().
styled
styled(tag: string | ComponentType, options?: StyledOptions):
(strings: TemplateStringsArray, ...values: Interpolation[]) => ComponentTypeAlso available as styled.div, styled.button, etc. via Proxy.
Creates a React component that:
- Resolves interpolations with component props + theme
- Hashes the resolved CSS string (FNV-1a, base-36)
- Injects the style rule if not already present (dedup via cache)
- Applies the generated class name (
vl-<hash>) to the element - Filters
$-prefixed transient props (and the injected contexttheme) from the forwarded props - Passes
ref(a regular prop in React 19) to the rendered element or component
Extending a styled component — styled(StyledComp) folds the base and extension templates into one component (extension wins, $-props reach the base, ${Base} selectors still match). See Extending Styled Components.
Component selectors — a static styled component interpolated in styled, css or createGlobalStyle resolves to its class selector; a dynamic one throws. See Component Selectors.
Static path (no function interpolations): CSS resolved once at creation time, zero per-render overhead. Dynamic path (function interpolations): CSS resolved per render, useRef cache avoids rehashing when unchanged.
keyframes
keyframes(strings: TemplateStringsArray, ...values: Interpolation[]): KeyframesResultReturns a KeyframesResult with:
.name: string— Animation name (vl-kf-<hash>).toString(): string— Returns.namefor use in CSS interpolations
The @keyframes rule is injected immediately and synchronously. No dynamic interpolation support (keyframes are always static). Deduplicated by animation name. On the server, the rule is shipped inside the <style precedence> tag of every component / global style whose CSS references it.
createGlobalStyle
createGlobalStyle(strings: TemplateStringsArray, ...values: Interpolation[]): FCReturns a React component that renders nothing on the client. Rules are mount-scoped and ref-counted:
- Static path: CSS resolved once at creation; inserted via
useInsertionEffectwhen the first instance mounts, removed when the last one unmounts - Dynamic path: CSS resolved per render with
{ ...props, theme }; a changed value releases the previous rules and acquires the new ones - SSR: Renders
<style precedence="low">(plus referenced@keyframes) for FOUC-free delivery; rules hydrated from SSR stay in place - CSS is unscoped (no
.vl-*class wrapper);@import/@charsetare inserted at the top of the sheet - Deduplicated by hash of resolved CSS (
g-<hash>)
Theme
ThemeProvider
type Theme = DefaultTheme & Record<string, unknown>
ThemeProvider: FC<{
theme: Theme | ((outer: Theme) => Theme)
children: ReactNode
}>React Context provider that makes a theme object available to all descendant styled components via props.theme. Pass a function to derive the theme from the outer one (theme={(outer) => ({ ...outer, accent: 'red' })}); the result is memoized on [theme, outer].
useTheme
useTheme<T extends Theme = Theme>(): THook to read the current theme from the nearest ThemeProvider. Returns {} if called outside any provider.
Hooks
useCSS
useCSS(template: CSSResult, props?: Record<string, any>, boost?: boolean): stringResolves a CSSResult to a class name string. Theme is automatically merged from context.
- Same injection mechanism as
styled()on the client (useInsertionEffect + dedup cache) - SSR: returns the deterministic class name but emits no CSS (no element to carry
<style precedence>); the rules are injected on hydration — usestyled()for content that must be styled in server HTML props— Additional props passed to function interpolationsboost— Double the selector for raised specificity
const highlight = css`
color: red;
font-weight: bold;
`
function Label({ children }) {
const className = useCSS(highlight)
return <span className={className}>{children}</span>
}StyleSheet API
sheet
import { sheet } from '@vitus-labs/styler'The global StyleSheet singleton used by all styled components and hooks. On the client, manages a single <style data-vl> DOM element.
createSheet
createSheet(options?: StyleSheetOptions): StyleSheetCreates an isolated StyleSheet instance. Use for SSR per-request isolation.
Sheet Methods
| Method | Returns | Description |
|---|---|---|
insert(cssText, boost?) | string | Inject scoped CSS, returns class name. Dedup via cache. |
insertKeyframes(name, body) | void | Inject @keyframes rule. Dedup by name. |
insertGlobal(cssText) | void | Inject unscoped global CSS. Dedup by hash. Not ref-counted. |
acquireGlobal(cssText, key?) | string | Ref-counted global insert used by createGlobalStyle — first acquire inserts the rules. Returns the key (g-<hash>). |
releaseGlobal(key) | void | Release an acquireGlobal; removes the rules when the count reaches zero (rules hydrated from SSR are kept). |
keyframesFor(cssText) | string | Server: the @keyframes rules referenced by cssText (empty when none). |
getClassName(cssText, boost?) | string | Compute class name without injecting (render-phase safe). |
prepare(cssText, boost?) | { className, rules } | Compute class + full rule text without injecting. For SSR <style precedence>. |
getStyleTag() | string | Complete <style data-vl="">...</style> tag with collected CSS. Manual mode only — empty under the default React 19 precedence path. |
getStyles() | string | Raw collected CSS rules string (no <style> wrapper). Manual mode only — empty under the default precedence path. |
has(className) | boolean | O(1) cache lookup for dedup check. |
reset() | void | Clear ssrBuffer, dedup cache and the insertCache / prepareCache lookups. Call between server requests. |
clearCache() | void | Clear the dedup cache plus resolve-side caches (insertCache, prepareCache, normCache). Keeps already-injected DOM rules. |
clearAll() | void | Everything clearCache() does, plus clear ssrBuffer, remove all DOM rules, and fire registered clearCallbacks so consumers (e.g. styled.ts's static caches) reset. Full HMR reset. |
cacheSize (getter) | number | Current number of entries in the dedup cache (rules known to be in the DOM). |
SSR — Default (React 19 <style precedence>)
On the server, styled components render <style href={className} precedence="medium"> elements alongside their DOM output (prefixed with any @keyframes the CSS references). React 19's streaming renderer hoists these to <head> automatically, dedupes by href, and orders them by precedence. This is the default path — no manual style collection needed.
Precedence levels:
medium— Component styles (fromstyled())low— Global styles (fromcreateGlobalStyle())
useCSS() is the exception: it has no element to attach a <style> to, so it emits no CSS on the server.
Hydration
On the client, StyleSheet.mount():
- Looks for an existing
<style data-vl="">element. If present, reuses its CSSOM sheet and seeds the dedup cache from any rules already inside it. Otherwise, creates a fresh empty<style data-vl="">. - Walks every
<style data-precedence][data-href]>tag React emitted during SSR and pre-populates the dedup cache with thosedata-hrefvalues. React merges same-precedence tags into one element whosedata-hrefis a space-separated list ("vl-a vl-b g-c"); every token is read (since 2.9 — previously all SSR rules were duplicated on hydration). This is what prevents the firstuseInsertionEffectfrom re-injecting a rule that's already in the DOM under a precedence tag. - On subsequent renders,
useInsertionEffectcache-hits and skips insertion for any class already known.
Manual SSR Mode (legacy / streaming)
For pipelines that need to collect CSS by hand (e.g. older SSR runtimes that don't process <style precedence>), opt in by calling sheet.insert() / sheet.insertGlobal() outside of render:
import { createSheet } from '@vitus-labs/styler'
// Per-request isolation
const sheet = createSheet()
// Manually push rules into the buffer (NOT done automatically — the default
// precedence path leaves ssrBuffer empty to avoid duplicate emission).
sheet.insert('color: red;')
// Render your app...
const html = renderToString(<App />)
// Extract collected CSS
const styleTag = sheet.getStyleTag()
// → '<style data-vl="">...all CSS rules...</style>'
// Or raw CSS for custom injection
const css = sheet.getStyles()
// Send to client
response.send(`<!DOCTYPE html><html><head>${styleTag}</head><body>${html}</body></html>`)
// Reset for next request
sheet.reset()Under the default precedence path, getStyleTag() and getStyles() return (nearly) empty output because component and global rules are never pushed to the buffer — they travel through React 19's collected <style precedence> tags instead. The one exception is keyframes() on the shared sheet: its @keyframes rule is also buffered at module load (until the first reset()), and since 2.9 it is additionally shipped inside the precedence tags of the components that reference it.
@layer Support
Wrap all scoped CSS in a CSS @layer:
const sheet = createSheet({ layer: 'components' })
// All CSS: @layer components { .vl-abc { ... } }Cache Eviction
- Default max cache size: 10,000 entries
- Applies to the cssText lookup caches (
insertCache,prepareCache): when exceeded, the oldest 10% of entries are evicted (Map insertion order) - The dedup cache of rules already in the DOM is never evicted — evicting it re-inserted live rules (duplicates + cascade reorder)
normalizeCSShas its own module-level cache, bounded at 2,000 entries with the same 10% eviction- Configurable via
createSheet({ maxCacheSize: 5000 })
Types
CSSResult
class CSSResult {
readonly strings: TemplateStringsArray
readonly values: Interpolation[]
toString(): string
}The return type of css(). A lazy container storing template strings and interpolation values. Resolves to CSS when consumed.
Interpolation
type Interpolation =
| string
| number
| boolean
| null
| undefined
| CSSResult
| CSSEngineResult // from @vitus-labs/core — lets config.css results type-check
| Interpolation[]
| ((props: {
theme?: DefaultTheme & Record<string, any>
[key: string]: any
}) => Interpolation)Values accepted in tagged template interpolation positions. A static styled component is also accepted at runtime and replaced with its class selector. The type is recursive — arrays can contain any interpolation type, functions can return any interpolation type.
StyledOptions
interface StyledOptions {
/** Custom prop filter. Return true to forward the prop to the DOM element. */
shouldForwardProp?: (prop: string) => boolean
/** Double the class selector for raised specificity (0,2,0). */
boost?: boolean
}StyleSheetOptions
interface StyleSheetOptions {
/** Maximum cached rules before eviction (default: 10000). */
maxCacheSize?: number
/** CSS @layer name to wrap scoped rules in. */
layer?: string
}DefaultTheme
interface DefaultTheme {}Empty by default. Extend via module augmentation for type-safe theme access.
Architecture
Resolution Flow
- Definition —
cssorstyledcaptures template strings and interpolation references - Resolution — At render time, function interpolations called with
{ ...props, theme } - Normalization — Single-pass cleanup: strip comments, collapse whitespace, remove redundant semicolons
- Hashing — FNV-1a hash of normalized CSS → base-36 string
- Deduplication — Cache lookup; if hash exists, reuse class name
- At-rule splitting — Extract @media/@supports/@container to top-level rules
- Injection —
useInsertionEffecton client,<style precedence>on SSR - Application — Generated class name (
vl-<hash>) applied to element
Hash Algorithm
FNV-1a (32-bit, 4-char unrolled loop) with base-36 encoding. Component classes are vl-<hash>, keyframes vl-kf-<hash>, global style keys g-<hash>. Boosted CSS is hashed with a suffix so it gets a different class from the same CSS unboosted.
The hash helpers (hash, HASH_INIT, hashUpdate, hashFinalize) are internal — they are not exported from @vitus-labs/styler.
Client Injection
A single <style data-vl> element is used for all injected rules. useInsertionEffect ensures rules are inserted synchronously before layout/paint, preventing FOUC.
Performance
| Metric | Value |
|---|---|
| Bundle size | ~7.0 KB min+gz, React external (18.94 KB minified) |
| Static path | O(1) per render |
| Dynamic path | O(n) per render (n = CSS string length) |
| Cache lookup | O(1) via Map |
| CSS insertion | O(1) amortized (CSSOM insertRule) |
| DOM elements | 1 shared <style> for all components |
Auto-Generated Types
StyledOptions
Prop
Type
StyleSheetOptions
Prop
Type
CSSResult
Prop
Type
Last updated on