DEV Community

Darren White
Darren White

Posted on • Originally published at darrenwhite.dev

16 6

Next.js: Replace React with Preact

One option to increase performance in production is to replace React with Preact. I can't take credit for this as in my case, I got the idea and code from https://leerob.io/.

Its' really simple to do, however a word of caution, this may not work if certain features of React are required in production. If you go down this route make sure you test fully before deploying to live.

To get started if you haven't already, create a next.config.js and include the following code

module.exports = {
  webpack: (config, { dev, isServer }) => {
    // Replace React with Preact only in client production build
    if (!dev && !isServer) {
      Object.assign(config.resolve.alias, {
        react: 'preact/compat',
        'react-dom/test-utils': 'preact/test-utils',
        'react-dom': 'preact/compat',
      });
    }

    return config;
  },
};
Enter fullscreen mode Exit fullscreen mode

The above checks that we are in production and the webpack function is being executed on the client side.

Don't forget to install Preact like i did, yarn add preact otherwise you'll get a build error for Module not found: React

Run yarn build to see the bundle size. I ran that before and after the changes, as you can see in the below screenshot the js size is about half:

React

React bundle size

Preact

Preact bundle size

Preact difference to React

If you use the preact-combat like in the example above then there is very little that isn't supported. For example, PropTypes are not supported in the core but are included in preact-combat.

A full list of what is and isn't included or is different can be found on the Preact website: https://preactjs.com/guide/v8/differences-to-react/

Resources

Repositories

Demo

Heroku

Build apps, not infrastructure.

Dealing with servers, hardware, and infrastructure can take up your valuable time. Discover the benefits of Heroku, the PaaS of choice for developers since 2007.

Visit Site

Top comments (1)

Collapse
 
qingzhoufeihu profile image
Jagger

Why don't we use Preact in both dev and prd environment

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay