DEV Community

Darren White
Darren White

Posted on • Originally published at darrenwhite.dev

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

Top comments (1)

Collapse
 
qingzhoufeihu profile image
Jagger

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