useStyles
useStyles is the React hook that connects a toned stylesheet to your component. It resolves tokens into platform-appropriate props (style, className, etc.) and applies variant matching based on the state you provide.
Signature
import { useStyles } from '@toned/react'
// Without variants
const s = useStyles(stylesheet)
// With variants
const s = useStyles(stylesheet, { variant: 'accent', size: 'm' })Parameters
stylesheet -- A stylesheet created with stylesheet(), optionally with .variants() chained. This is the style definition to resolve.
state -- An object of variant key-value pairs. Required when the stylesheet has required variants; omit when there are no variants. TypeScript enforces correctness here.
Return Value
An object with one key per element defined in the stylesheet. Each value is a props object that can be spread onto a JSX element:
const s = useStyles(buttonStyles, { size: 'm', variant: 'accent' })
// s.container => { style: {...}, className: '...' }
// s.label => { style: {...}, className: '...' }
return (
<button {...s.container}>
<span {...s.label}>Click me</span>
</button>
)How It Works
Under the hood, useStyles reads the active config (set by setConfig in your config file) and calls the stylesheet's initialisation function. It caches the result in a ref and only re-initialises when the stylesheet reference changes. When the state object changes, it calls an internal applyState method to update variant matching without re-creating the full style map.
Usage Patterns
Static Styles (No Variants)
For stylesheets without variants, call useStyles with just the stylesheet:
const cardStyles = stylesheet({
card: { bgColor: 'elevated', borderRadius: 'large' },
})
function Card({ children }) {
const s = useStyles(cardStyles)
return <div {...s.card}>{children}</div>
}Dynamic Variants
For stylesheets with variants, pass the variant state as the second argument. The hook will update whenever the state changes:
function NavLink({ href, label, isActive }) {
const s = useStyles(navStyles, {
active: isActive ? 'true' : undefined,
})
return <a href={href} {...s.link}>{label}</a>
}Forwarding Props
Since useStyles returns plain props objects, you can combine them with additional props:
function Input({ error, ...rest }) {
const s = useStyles(inputStyles, { error: error ? 'true' : undefined })
return <input {...s.input} {...rest} />
}