Table of contents
1.
Introduction
2.
What is Code Splitting?
3.
What is Dynamic Code Splitting?
4.
Different Types of import and exports used in Code Splitting
4.1.
With Custom Loading Component
4.2.
Dynamic Component With Named Exports
4.3.
Disable Server-Side Rendering
4.4.
With suspense
5.
Loading Effect
6.
FAQs
7.
Key Takeaways
Last Updated: Mar 27, 2024

Code Splitting in Next.js

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction


Websites offer visitors the advantage of not having to download entire applications before using them. Code splitting provides a similar feature of allowing visitors to download an application incrementally. 

When you code-split your app, you can "lazy-load" only the information that a user needs at that moment, improving performance dramatically. Although you didn't reduce the total amount of code in your app, you avoided loading code the user may never use and reduced the amount of code that must be loaded initially. Next.js provides React-based applications with multiple functionalities.

What is Code Splitting?

By splitting your code into multiple pieces, you can reduce your bundle size in two ways: Your application will load faster, and you will reduce the size of its payload.

Adding bundles to your app is excellent, but keep in mind that your bundle will grow with it as your app grows, mainly if you include large third-party libraries. To avoid making your bundle too large and making your app too slow to load, you need to keep track of the code you include in your bundle.

Get ahead of the problem and start breaking up your bundle as soon as possible, so you don't wind up with a large bundle. It can be used by bundlers like Webpack and Browserify (via factor-bundle) to load multiple bundles at runtime dynamically.

You can introduce code-splitting into your app with the help of dynamic import() syntax.

What is Dynamic Code Splitting?

Dynamic imports are different from regular import modules in that they can be loaded at any time. It is possible to request dynamic imports at the use time instead of forcing them to be loaded at reading time. The module can be split up into a separate bundle file to be fetched separately, thus reducing the initial page load time.

Loadable components also support dynamic imports. This automatically handles all types of edge cases, so you can easily split your code!

Our React app can be code split with Next.js using ES2020 dynamic import().

With the import statement, Next.js's next/dynamic module is imported.

Whenever import is called as an argument, this function will receive it. The path to the component file is passed as an argument to import.

 

pages/example.js

import dynamic from 'next/dynamic'
const newComponent = dynamic(() => import('../components/example'))
function newComponent() {
 return (
   
<div>
        
   <Header />
        
   <newComponent />
        
   <p>Dynamic import example</p>
      
</div>
 )
}
export default newComponent

 

As you can see, newComponent is a separate bundle from the main bundle. The split into manageable chunks in ../components/example makes Next.js able to Server-Side render the newComponent from the server. The following example shows how to use the newComponent component as a component.  

 

components/app.js

function App() {
   return (
       
<div>
              
   <newComponent />
          
</div>
   )
}

 

When the App component is rendered, the newComponent component in ../components/example is loaded due to the dynamic() function call.  

Different Types of import and exports used in Code Splitting

With Custom Loading Component

If there is a delay in loading resources, it is good to provide a loading indicator. Adding a component to display the component as soon as it loads would be another option.

The following can be written as:

components/app.js

function app() {

  return (

    <span>Coding Ninjas</span>

  )

}

export default app

 

pages/example.js

import dynamic from 'next/dynamic'
const value_Component = dynamic(() => import('../components/app'), { loading: () => 
<p>Please wait loading…</p>
})
function newComponent() {
 return (
   
<div>
    Custom loading 
    <value_Component />
</div>
 )
}
export default newComponent

 

A loading property is set on a component in the code of an object.

Dynamic Component With Named Exports

You may use a named export for dynamic components that are not the default exports.

We can do that by writing:

components/app.js

export function app({ }) {

  return (

    <h1>Coding Ninjas</h1>

  )

}

 

pages/example.js

import dynamic from 'next/dynamic'
const value_Component = dynamic(() => import('../components/app').then((mod) => mod.Name)
)
function newComponent() {
 return (
   
<div>
    Named import 
    <value_Component />
</div>
 )
}
export default newComponent

 

We retrieved the newComponent from the module in the callback using the then callback.

Disable Server-Side Rendering

Sometimes, you might not need to include a module on the server. For instance, a module may include a library that only works in the browser.

By setting the SSR property of an object to false, the dynamic function will disable server-side rendering.

components/app.js

function app() {

  return (

    <h1>Coding Ninjas</h1>

  )

}

export default app

 

pages/example.js

import dynamic from 'next/dynamic'
const value_Component = dynamic(() => import('../components/app'), { ssr: false }
)
function newComponent() {
 return (
   
<div>
    With no SSr
    <value_Component />
</div>
 )
}
export default newComponent

 

With suspense

The fallback only works on the client or server-side. We are still working on fully supporting SSR in concurrent mode.

At load time, @loadable/component exposes a lazy method similar to React.lazy.

import React, { Suspense } from 'react'
import { lazy } from '@loadable/component'
const value_Component = lazy(() => import('./value_Component'))
function newComponent() {
 return (
   
<div>
         <Suspense fallback={
    <div>Loading...</div>
    }>
           
    <value_Component />
         </Suspense>
       
</div>
 )
}

 

It's as simple as that! It will automatically be loaded and rendered when you use LoadableDashboard in your application. Fallback components are placeholders shown during the actual components load.

Loading Effect

Since we haven't implemented any visual cues yet, the user will not know when a component chunk is loaded from a code split. The user must be notified if something is being loaded or will be rendered soon because this is a bad design.

Loading effects, such as Loading..., must be added. The dynamic() function takes a second argument to accomplish this. It takes an object as a second argument. The object is assigned a loading property with a function value that returns HTML. This HTML will be displayed as a loading visual cue as the code split loads.

 

pages/example.js

import dynamic from 'next/dynamic'
const value_Component = dynamic(() => import('../components/app'), 
{ 
   loading: () => <i>Loading...</i> })

 

When new_Component is being loaded, our loading effect indicates that <i>Loading...</i> is taking place.

FAQs

  1. Why do we use Dynamic imports?
    The dynamic import process is a bit more complicated than a regular import,  let’s see the reasons for that:
    Speed Up Page Load: It's only useful if the code you're dynamically importing is large enough to slow down the loading of your page and if the code you're dynamically importing isn't needed most of the time.
    Reduce Memory Usage: Modules can also be dynamically loaded to reduce memory usage. It may be a good idea not to load modules that are rarely used, such as admin-only modules, if they spike your memory usage when loaded.
    When The File Name Is Dynamic: A translation file is an excellent example since you cannot tell the user's locale beforehand.If you were creating a rendering engine that could render a bunch of different shapes defined in various modules, what would it look like? In that case, you can let the shapes you are rendering determine which modules to import instead of importing them all at once.
    Browser Support: Though ES2020 is a relatively new standard, the browser supports dynamic module imports very well. At this time, the only unsupported browsers are Internet Explorer 11 and older versions of Edge. Fortunately, you can add dynamic imports and code splitting to older browsers using tools like webpack and babel.
     
  2. How fast is the next.js compared to React?
    Next.js' server-side rendering and static sites of Next.js make it possible to build fast applications. The Next 10's new features, such as Image Optimization, are effective by default. So, saving time and improving performance can be achieved with Next.js if you choose it. The added benefit of SSR (Server Side Rendering) is that your application will be much faster.
     
  3. What are the benefits of code splitting?
    With code splitting, you can break a bundle up into many smaller bundles, and if you change one of them, none of the others need to be reloaded since they haven't changed. It is faster for the site when resources don't have to be reloaded as often.
     
  4. How does the Next dynamic work?
    This tool allows you to import and work with JavaScript modules dynamically. Moreover, it supports SSR as well. Dynamic imports can be considered a similar method for dividing code into manageable pieces.

Key Takeaways

Here's what we learned about code-splitting and how it affects front-end performance.

And also how to code split React components using Next.js dynamic import() and how to use named exports. We have also learned how to set a loading indicator to display the loading status of dynamic components.

Even though dynamic imports are not often needed, knowing what they are and how to use them is still a beneficial skill to possess. Dynamic imports are a great solution to page load speed issues or memory issues.
 

Learn more about other areas of development if you are a newbie to Web development. We have a guided path for you to follow.

Live masterclass