Dark theme with Stitches
Integrate dark theme support with Stitches on Gatsby.
After tinkering a bit with Stitches, I am very excited to see the improvements in DX, variant-first support, and performance in the CSS-in-JS space! Definitely give their documentation a peruse to see all the brilliance being done.
While exploring this library, I found a small theming gotcha when integrating it with my Gatsby static site. If you are curious about using Stitches with Gatsby supporting a dark theme, read on to see my current solution.
Switching to Stitches
As an experiment, I decided to swap out styled-component with @stitches/react to test out Stitches' developer experience and performance. I was also curious about the effort of migration and what was required to support my site's dark theme.
Swapping components was very straightforward, especially with the help of the CSS-in-JS VS Code plugin. My initial reason for authoring my components using the tagged template literal method was to maintain closer compatibility with CSS. However, object styles are well supported the JS community and a versatile structure for storing styles.
A small plus, object styles are also a tad faster than runtime-parsed template strings. They also work better with libraries that support a typed interface (ex: vanilla-extract, Stitches).
Theming with Stitches in Gatsby
Back to the theming problem! The only other migration step was to update the theming layer. I followed the dark theme pattern well explained and shared from Josh Comaeu – thanks Josh! Using the Stitches getCssString helper, I simplifed my code a good bit. Stitches handles the addition of CSS custom properties based on your theme configuration, allowing me to remove the chunk of code that was manually handling this step.
Here is the final required code used in the site's SRR step: