AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

StyledComponents: Css Prop Hoisting Causes "Cannot Access 'X' Before Initialization"

Next.js SWC styled-components transform hoists the css prop to the styled component declaration, causing a ReferenceError due to temporal dead zone when the css prop references a const declared later in the module.

highConfidence 90%Next.jsAffected V16.4.0-Canary.20

Origin Analysis

The SWC styled-components transform converts the css prop into a styled(...).withConfig(...) template literal at the point of the styled component declaration. If the css prop interpolates a variable declared later (e.g., const COLOR = 'red' after const Box), the transformed code reads the variable before its lexical binding is initialized, triggering a ReferenceError due to the temporal dead zone.
1. Clone https://github.com/BrianMwit/next-styled-component-issue-repro 2. Run npm install 3. Run npm run dev or npm run build 4. Observe ReferenceError: Cannot access 'COLOR' before initialization at app/page.tsx:9:30

Fixing Code Block

Edge Case Audit

This workaround only addresses this specific ordering. Any other variable referenced in a css prop must also be declared before the styled component, which may be impossible for cyclic or cross-module dependencies. Rolling back is as simple as reverting the variable order; however, the original bug will return until Next.js fixes the transform. Also, HMR and SSR builds can still fail if references remain in a later scope. Use styled templates directly or CSS custom properties for more robust dynamic styling.

Ecosystem Topology