I don't have the energy to debunk some of these replies, but let me quickly say:
1. The reason that this is a hard problem has nothing to do with React, or Gatsby. It has to do with the strategy of precompiling HTML and not having a runtime server, an approach with many many benefits (described here: https://joshwcomeau.com/gatsby/a-static-future/). If you're wondering why anyone would put up with all this tomfoolery for a dark mode, please read that so you can understand the benefits to this approach.
2. "React is overkill for static sites" is a debate I am not trying to have, but I can say that for my blog (the site that this post is about), React has allowed me to do lots of cool things that would have been much harder otherwise. And using Gatsby means that I have first-meaningful-paint performance that beats a PHP template with no JS, since my site doesn't have to do any database lookups or real-time HTML generation. I am not saying that this is the right approach for every website, but it was 100% the right choice for this one.
4. Many of these replies are making suggestions that are discussed in the article itself. CSS variables are not an alternative to this solution, they _are_ the solution (my solution wouldn't work without them!). Please read the post before forming an opinion about it.
I hope that helps clarify some things! Hope you're all doing alright and staying home.