Style Hooks

Style hooks

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

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

If you're feeling frisky, supercharge your style hooks with @style-hooks/styled to add a styled-components-like API to the mix.

Play with the below code on CodeSandbox

npm i @style-hooks/core @emotion/core
/** @jsx jsx */
import React from 'react'
import ReactDOM from 'react-dom'
import {css, jsx} from '@emotion/core'
import {createStyleHook, createElement, ThemeProvider} from '@style-hooks/core'
// Your very own style hook
const useBox = createStyleHook('box', {
w: (value, theme, props) => css`
width: ${value + theme.box.sizeUnit};
`
})
// Accompanying component w/ style props using
// your style hook
const Box = props => {
props = useBox(props)
// createElement here provides this component
// an 'as' prop
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>'}. Resize the screen to change my color.
</Box>
</ThemeProvider>
)
const rootElement = document.getElementById('root')
ReactDOM.render(<App />, rootElement)

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.

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.

Adding @style-hooks/styled to the mix only adds an additional 3kb.

Continue to Theming
NPM icon
MIT License ©2019
Jared Lunde