I made my website with Next JS, an excellent react framework for making production-ready websites. The downside to React frameworks is that they can ship a lot of js to the browser, which comes at a performance cost. Luckily, you can take some steps to optimize this, and replacing React with Preact is one of them.
Now I do not want to take any credit for this tip. I saw it in a video from Vercel's Director of Developer Relations, Lee Robinson. Switching it out is easy as long as you are not using any of these features. So without further ado, here is what you need to do:
Install Preact:
npm i preact
Add this snippet to your next.config.js file:
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;
},
};
And that's it. Now Preact will be used in production builds instead of React. This website now uses Preact. Before the switch, 91.8 kb of js was loaded in the browser without caching. After the switch, 55.5 kb of js was loaded when testing the same site.
NB! This implementation doesn’t currently work with React 18
Originally posted on aamodt.xyz
Top comments (3)
wow almost half the size. That's pretty crazy. I've been thinking of taking more of a look a preact. Curious, to reduce that size what exactly does preact do?
Yeah, it's pretty crazy! You can read about what preact does different to react here. 😊
Cool thanks for sharing