Style hooks

Turn your React function components into responsive components with style props using Style Hooks and Emotion

Use @style-hooks/core to seamlessly add themes, CSS-in-JS styles, variants, breakpoint props, a css prop, and an as prop to any React function component

Play with the below code on CodeSandbox

npm i @style-hooks/core @emotion/core
/** @jsx jsx */
import React from 'react'
import {css, jsx} from '@emotion/core'
import {useStyles, createElement, ThemeProvider} from '@style-hooks/core'
// The config for your style hook
const boxConfig = {
name: 'box',
styles: {
w: (value, theme, props) => css`
width: ${value + theme.box.sizeUnit};
`,
}
}
// Your very own style hook
const useBox = props => useStyles(boxConfig, props)
// Accompanying component w/ style props using
// your style hook
const Box = props => {
props = useBox(props)
// createElement here provides this component
// an 'as' prop and turns the 'css' prop generated
// by useBox() into a class name and CSS styles
return createElement('div', props)
}
// The theme for your app
const theme = {box: {sizeUnit: 'px'}}
// Usage w/ theme
const App = () => (
<ThemeProvider theme={theme}>
{/*
Shows off the 'as' prop,
followed by 'breakpoint props',
followed by the 'css' prop
*/}
<Box
as='main'
w='200:phone 300:tablet'
css={
theme => css`
@media ${theme.breakpoints.phone} {
height: 200px;
background-color: hotpink;
}
@media ${theme.breakpoints.tablet} {
height: 300px;
background-color: skyblue;
}
`
}
>
Hello world from this {'<main>'}
</Box>
</ThemeProvider>
)

Install it

npm

npm i @style-hooks/core @emotion/core

yarn

yarn add @style-hooks/core @emotion/core

Getting the most out of Style Hooks

Style hooks are an incredibly powerful pattern as noted above. I highly recommend that you utilize them by creating component primitives for things like <Box>, <Text>, <Grid>, et. al. I also highly recommend you embrace the kind prop as often as possible to maximize any memoization and deduplication opportunities. For example, this documentation site uses them for creating h1, p, a, and numerous other variants in its <Text> component.

Maximizing performance

Emotion itself does a pretty good job in memoizing CSS definitions it receives, but you can and should take this further by memoizing your functional style props as often as possible. The theme is immutable so you can safely memoize the first two arguments of your functional style props. Not sure what functional style props are? Check out the Create a Style Hook page.

Big functionality in a small package

By using style hooks you're getting a ton of functionality for less than 3kb gzipped. You'd be hard pressed to find another library which provides all of the same features in such a small package.

Continue to Theming