DEV Community

Cover image for Replacing React with Preact. It was easy and worth it.
Stan Bright for SaaSHub

Posted on

Replacing React with Preact. It was easy and worth it.

I had been considering preact for quite some time. After all, the sell is easy:

  • 100% compatible with the React ecosystem (kind of)
  • Much smaller (js bundle size)
  • Faster (performance)

About two years ago, I went to a local meet-up in Sydney where the presenter was sharing how they were integrating Preact successfully in some parts of Qantas. That was interesting. And he was convincing. Yet, given that everyone is using React, I thought it was a daunting task and never put the time to research it further. Until recently.

I was working on optimizing the page-load speed of SaaSHub, and one of the paths was decreasing the JS bundle size. I played a bit with webpack-bundle-analyzer and source-map-explorer, and it was apparent that 35% of all the libs were taken by React & react-select. Then I remembered preact... and decided to review it again.

It happened that that task was more scary than difficult. After going through the docs, the whole switch to preact consisted of adding it to packages.json, adding the relevant aliasing to webpack's build configs:

environment.config.resolve.alias = {
  "react": "preact/compat",
  "react-dom/test-utils": "preact/test-utils",
  "react-dom": "preact/compat",
  // Must be below test-utils
}

module.exports = environment
Enter fullscreen mode Exit fullscreen mode

and importing 'preact/debug' somewhere in the app:

import 'preact/debug'

That was all. So simple. Everything worked without touching another line of code. Of course, the process could be more complicated for web apps with more sophisticated code.

What are the benefits:

  • SaaSHub's JS bundle file-size decreased with 20%: from 577k down to 460k
  • Faster JS (although I haven't benchmarked that, neither have felt it being slow)

In the end, if you are working on optimizing your JS, and you don't have super complicated setup, I'd highly recommend giving preact a go. It might be easier than you think.

p.s. the next step will be replacing react-select with downshift. I've already implemented one small component with it, and it is amazing. Unfortunately, that migration will require a lot more code changes.

Top comments (4)

Collapse
 
ac37s profile image
e1cb4 ac37s

"100%" and "kind of" are not
"kind of" compatible

Collapse
 
stanbright profile image
Stan Bright

Of course. But in many cases it will feel like a drop-in replacement. Which is "kind of" 100% compatible :D

Collapse
 
seanmclem profile image
Seanmclem

Would I need to eject from CRA?

Collapse
 
dollier profile image
Dorian C

For simple project I totally agree, but sometimes preact is a bit behind when there is a new version of react (hooks for example).