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
-
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.
-
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.
-
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.
-
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.