
Next.js ships with a solid set of built-in performance primitives, but knowing which lever to pull — and when — is what separates a snappy app from a sluggish one. Here are six optimization techniques worth adding to your workflow.
Code Splitting#
Next.js automatically supports Code Splitting, allowing you to split your code into various bundles which can then be loaded on demand or in parallel.
import dynamic from 'next/dynamic'
const DynamicComponent = dynamic(() =>
import('../components/hello')
)
function Home() {
return <>
<Header />
<DynamicComponent />
<Footer />
</>
}
export default Home
Server Side Rendering (SSR) and Static Site Generation (SSG)#
Next.js supports both SSR and SSG. Use these rendering strategies wisely based on content needs — dynamic vs static. SSG is great for SEO and performance as it pre-renders the page at build time.
export async function getStaticProps(context) {
const data = await fetchData();
return {
props: {data}, // will be passed to the page component as props
}
}
Remove Unused Code#
Ensure that you only import what you need. With TypeScript, make sure that any unused variables or methods are removed or commented out if not required.
Optimize Images#
Use the built-in Image component in Next.js which provides lazy-loading by default.
import Image from 'next/image';
<Image src={src} alt={altText} width={500} height={300} />
Avoid Blocking Loops#
In JavaScript, loops can block the event loop and slow down your application. If you have an array that contains a large amount of data, consider breaking it up and using async/await.
const processArray = async (data) => {
for (let item of data) {
await processData(item)
}
}
Short-circuit Evaluation for Optional Rendering#
Short-circuit is evaluated faster than ternary operation particularly when it comes to optional rendering.
{
data && <DataDisplay data={data} />
}