Introduction
We all know Next.js is quite heavyweight, especially compared to Svelte Kit or Nuxt.js and optimization is not everyone’s favorite thing. Your product owner might not want to waste time on optimization and prefer shipping features. Your QA and tester might not want to regression-test all the features that might be affected.
This article is a simple tutorial on Next.js optimization, so you can achieve better performance, lighthouse score… in the shortest amount of time
Relocate your third party scripts
If your app has Google Analytics, Hotjar, Facebook Pixel…or any third-party scripts. You might want to relocate those scripts onto service workers and off the main thread.
I have an article about this right here
Trust me, it won’t take long and the results might surprise you.
Use dynamic imports
Next.js supports lazy loading external libraries with import()
and React components with next/dynamic
. Deferred loading helps improve the initial loading performance by decreasing the amount of JavaScript necessary to render the page. Components or libraries are only imported and included in the JavaScript bundle when they're used.
next/dynamic
is an extension of React.lazy
. When used in combination with Suspense
, components can delay hydration until the Suspense boundary is resolved.
For instance, my home page has 4 big blocks, but only one of them shows at the first load, user has to scroll to see other blocks. So I don’t want all 4 to load at first:
const Overview = dynamic(() => import('./Overview'));
const Project = dynamic(() => import('./Projects'));
const Contact = dynamic(() => import('./Contact'));
Now let’s look at the results
Before:
After:
You can see the first load JS is reduced from 115kb to 100kb, not much, but it is honest work
Preact instead of React
Next.js is built on top of React, but Preact is a JavaScript library, considered the lightweight 3kb alternative of React with the same modern API and ECMA Script support.
So if your app is just a common Next.js app, I don’t see any reason to not use Preact. Its downside is just a lack of community support.
How to implement:
First, you have to install Preact
Open your next.config.js
file and reassign react:
webpack: (config, { dev, isServer }) => {
if (!dev && !isServer) {
Object.assign(config.resolve.alias, {
react: 'preact/compat',
'react-dom/test-utils': 'preact/test-utils',
'react-dom': 'preact/compat',
});
}
return config;
},
Now look at the performance:
The bundle size is significantly smaller.
But not just that, let’s see it in production:
Before
After
You can see all JS files are smaller.
Conclusion
There are many other ways to improve your app performance out there, but they require more work and research.
I hope the methods above work for you, if not, please comment down below and we can find the best way!
Last Words
Although my content is free for everyone, but if you find this article helpful, you can buy me a coffee here
Top comments (0)