Replacing Styled-Components with Nano-CSS in a React Project

Tomasz Samczynski
2 min readMar 24, 2021

I’ve been working on a project and want to trim all the dependencies to be smaller. Smaller bundle means faster load time. For easier styling of components we often install popular libraries to help us develop faster. Sometimes there exist faster, smaller alternatives; this is one such case.

The size is not terrible but every KB counts

So an intro to nano-css can be found on their github page along with performance benchmarks.

Assuming that you already use styled components, your syntax looks kinda like this:

import react from 'react';
import styled from 'styled-components';
const Button = styled.a`
display: inline-block;
border-radius: 3px;
padding: 0.5rem 0;
`;
const SomeParent = () => {
useEffect(() => {
// do something
});
return (<div>
<span>
<Button>Button Text</Button>
</span>
</div>);
};

This same thing can be achieved with nano-css like such:

// first the setup, which is longer that styled components:import { createElement } from 'react';
import { create } from 'nano-css';
import { addon as addonJsx } from 'nano-css/addon/jsx';
import { addon as addonRule } from 'nano-css/addon/rule';
const nano = create({
h: createElement,
});
addonRule(nano);
addonJsx(nano);
export const { jsx } = nano; // I would export this from a different file so that I have a reusable object
// now you can style an anchor tag, the only difference is object notation.
const Button = jsx('a', {
display: 'inline-block',
'border-radius': '3px',
padding: '0.5rem 0',
});
// sample usageexport const MyComponent = () => {
useEffect(() => {
// do something
});
return (<div><span><Button>Text</Button></span></div>);
};
Look at those savings!!!!

Now you can speed up your page load by that tiny bit. Every KB counts.

--

--