css.compose API helps you build reusable components by extracting styles into your stylesheet. Styles in the compose block are replaced with a class name, reducing repetition in your markup.
Basic Usage
Define a composed style and destructure the returned function to getcn (className) and css (style) functions:
Generated Output
The composed styles are extracted into your CSS file with a generated class name:Return Value
Callingcss.compose() returns a generator function. When you call this generator, it returns a tuple:
A function that combines the generated class name with any additional class names you pass. Filters out falsy values automatically.
A function that accepts override styles, similar to the
css utility. Use it to apply inline overrides or pass through props.Real-World Example
Here’s a complete button component from the Tokenami examples:Input Parameters
Thecss.compose() function accepts a configuration object:
Base styles that will be extracted into the CSS file. These properties follow the same syntax as the
css utility.Extend styles from other composed styles or css utilities. See Extending Styles for details.
Performance Benefits
Usingcss.compose provides several performance and developer experience benefits:
Reduced Markup Size
Instead of repeating inline styles on every element:Cleaner Components
Extract style definitions to keep your component logic clean and maintainable. Styles are defined once and reused across all instances.Caching
Tokenami caches composed styles using an LRU cache, so repeated calls with the same configuration are instant.When to Use Compose vs CSS Utility
Usecss.compose when:
- Building reusable components with consistent styles
- You have many instances of the same component
- You want cleaner markup
- You need variants (see next section)
css utility when:
- Prototyping or one-off styles
- Styles are highly dynamic and change frequently
- Building utility components that are heavily customized by consumers