Code Splitting in Next Js

Jayesh bhade
Groww Engineering
Published in
3 min readOct 21, 2022

--

Let's split our application code to load it super fast 🚀

What is code splitting?

Code splitting is the splitting of code into various bundles or components which can then be loaded on demand or in parallel.

As an app grows its bundle size will grow too and at some point in time its bundle will become so large that it will take a long time to load. Less loading time enhances the user experience as a whole and also helps in better SEO. The benefits of code splitting are :

  • The speed at which a website loads and displays content becomes faster.
  • The time intervals between when a user requests an action, and when the user gets a result i.e. Time to Interactive, improves.
  • The rate at which users exit the webpage without interacting with the site decreases.
  • Helps in increasing site conversion rates.

How to import a component?

// for default exportsimport AppComponent from ‘./AppComponent’;// for named exportsimport { OtherComponent } from './AppComponent';

How to import dynamically in React?

import React from 'react';// for default exportsconst DynamicComponent = React.lazy(() => import('./AppComponent'));

React.lazy currently only supports default exports. If the module you want to import uses named exports, you can create an intermediate module that re-exports it as the default.

How to import dynamically in Next js?

import dynamic from 'next/dynamic';// for default exportsconst DynamicComponent = dynamic(() => import('../AppComponent'));// for named exportsconst DynamicComponent = dynamic(() => import('../AppComponent').then((AppComponent) => AppComponent.OtherComponent));

The next/dynamic module implements lazy loading imports of React components and is an extension of React.lazy .

What to show user in the time between the component getting imported and shown to user? 🤔

If working on the latest version of React.js, suspense can be used

import { Suspense } from 'react';
import dynamic from 'next/dynamic';
import Loader from './Loader';const DynamicComponent = dynamic(() => import('../AppComponent'), { suspense: true });

export default function App() {
return (
<Suspense fallback={<Loader />}>
<DynamicComponent />
</Suspense>
)
}

Just set the suspense attribute as true. The page will render the Suspense fallback first, followed by the DynamicComponent when the Suspense boundary is resolved.

If working on an older version of React.js, loading attribute can be used

const AppComponent = dynamic(() => import('../AppComponent'),{
loading: () => <Loader />,
})

For Client Side Rendering of components, we can disable Server Side Rendering (SSR) for components that do not require much user interaction or have external dependencies. ssr attribute can be set as false , to render on the client side.

const AppComponent = dynamic(() => import('../AppComponent'),{
ssr: false,
})

External dependencies can be very large sometimes. Apart from importing local components, we can also add a dynamic import for external dependencies. For example, here I imported dayjs dynamically in onClick function.

const dayjs = (await import("dayjs")).default;

Conclusion

Dynamically importing modules reduces the initial bundle size, allowing for a smaller initial load since the client doesn’t have to download and execute as much, saving bandwidth.

If you’re lazy-loading a component that’s needed for the initial render, it may unnecessarily result in longer loading times. Try to only lazy load components that aren’t visible on the initial render.

If you’ve enjoyed this story, please click the 👏 button and share it, so that others can find it as well! Also, feel free to leave a comment below.

Groww Engineering publishes technical anecdotes, the latest technologies, and better ways to tackle common programming problems. You can subscribe here to get the latest updates.

We are hiring. View job openings here.

--

--