United Kingdom: +44 (0)208 088 8978

Using Preact with SAFE Stack

Matt shows how easy it is to swap a SAFE Stack app from React to Preact.

We're hiring Software Developers

Click here to find out more

Preact is a "Fast 3kB alternative to React with the same modern API".

Of most interest to us, there is a compatibility layer, preact/compat, which aims to make code written to work against React (including third-party components) work without change, but benefit from smaller bundle size and some other differences.

How to swap to Preact

Swapping a SAFE Stack app to Preact is easy. All you need to do is replace the dependencies in package.json from "react" and "react-dom" to "preact":

-                "react": "^17.0.2",
-                "react-dom": "^17.0.2"
+                "preact": "^10.13.1"

(You can also do this via the npm CLI: npm uninstall react; npm uninstall react-dom; npm install preact.)

Then alias from the replaced packages to "preact/compat" in webpack.config.js (ensuring that any JavaScript code uses 'react'/'react-dom' imports continues to work):

+        },
+        resolve: {
+            alias: {
+                "react": "preact/compat",
+                "react-dom": "preact/compat"
+            }

I've made a GitHub repo with the changes applied; you can see the diff in the relevant commit.

After doing that, the SAFE Todo app still works as expected:

SAFE Todo app showing a task for testing the app with Preact

But the bundle size is smaller. Before:

Browser network tab showing 854 kB vendors bundle

After:

Browser network tab showing 307 kB vendors bundle

Conclusion

Swapping to Preact in a SAFE Stack app was remarkably easy. The code continues to work, but the vendors bundle size is significantly smaller. This could be a topic that's worth exploring further!