cva-best-practices
cva best practices
Use the project's styling approach and component conventions. Apply the guidance below to the requested component rather than refactoring unrelated code. The beta docs are the source of truth for these recommendations.
Check the installed package
Read the consuming package's manifest, lockfile, and existing imports before choosing an API. cva@1.0.0-beta.x and class-variance-authority@0.x are different packages. Beta releases can change without semver guarantees; verify the installed exports and types when an API below is unavailable. Do not upgrade dependencies as part of ordinary component work.
This guidance targets the cva 1.0 betas (verified against cva@1.0.0-beta.12): the single-object cva call, composes, defineConfig from cva/config, and getSchema from cva/tools. Older betas may have different entry points or APIs. For stable class-variance-authority, follow the stable docs: import from class-variance-authority and use cva(base, options). Do not apply beta-only configuration, composition, schema, or Tailwind CSS exports to stable projects. When an upgrade is requested, consult the release-specific migration guidance instead.
Define variants once
- Define a class function outside the component render body. Put invariant classes in
base, independent choices invariants, and combinations incompoundVariants. - Prefer framework prop defaults in React, Svelte, or Vue wrappers so the same value reaches styling and markup.
defaultVariantsonly supplies defaults inside the class function; it cannot set an element's attributes. Use it when the class function should supply defaults to its callers. Omitted props andundefineduse those defaults. Avoid duplicating defaults in both places, and remembergetSchemacannot read framework prop defaults. - To select no classes for a variant, declare a named option such as
unset: null, then pass"unset". Do not assume passingnulldisables a beta variant. - Treat the configuration and referenced objects as immutable after creating a class function. Create another function if the configuration changes.
- Prefer server-side rendering or static generation for static components when the framework permits it. Do not add client-side JavaScript solely to generate a static class string.
See Variants, Default variants, and the cva API reference.