Speed Up React Native Development with Utility Stylesheets 🚀
I've relaunched my YouTube channel!
You can make your React Native development experience significantly faster by creating precompiled utility classes that make styling most components as easy as using Tailwind CSS on the web.
When you first started building apps with React Native, you probably used inline styles. These are the object literals that you can directly insert onto the
property of your components, like this View tag.
But, these come with some performance issues. In React Native, every time a component rerenders, this object literal will get recreated. This means React Native will have received, in its opinion, a brand new style object that needs to be passed over the Native bridge and repainted, even if all the keys on the style object are exactly the same as before.
The most common way to deal with this is by creating a
for your component. This allows React Native to send your styles over the Native bridge just once, and then refer to the resulting style by a numerical ID. Now when your component rerenders, the style ID is compared and found to be equal, resulting in no further rerenders.
However, when you're building a lot of new components, you'll find yourself constantly rewriting the same styles over and over again: Margin 8, Padding 16, Border Radius 4..., and often these styles are applied alone to View elements.
So, we can take a massive shortcut when building new components by creating precompiled utility classes.
We can build a function that creates named utility properties for Border Radius, Margin and Padding with all the right Typescript info with just a few arrays and loops.
Let's start with our property keys. These arrays define everything we need to build our property keys. Border radius is not in the first array as it only has four other keys for the corners.
The CoverTypes array lets us add the permutations for horizontal, vertical, top, etc, like MarginTop, for example.
Next we define the Intervals we want, this determines whether we have MarginTop6, MarginTop7 and so on. We'll go with [2, 4, 6, 8, 12, 16, 24, 32]
You might have noticed the arrays above are defined as const, which means their values never change and allows Typescript to know exactly what literals exist inside them. This means we can construct Typescript Template Literals, using the backtick quote and string interpolation.\