Code splitting is a technique in modern web development that aims to reduce the size of JavaScript bundles sent to the client by splitting the code into smaller, separate parts. In Next.js, code splitting is an automated process that offers significant performance benefits.
Next.js implements automatic code splitting by loading each page in its own JavaScript bundle. This means that for each page, only the code that is actually needed is loaded. This reduces the initial load time as the browser does not have to load all the JavaScript for the entire application.
If you have a Next.js application with pages in
pages/index.js
and pages/about.js
, Next.js
creates separate JavaScript bundles for each page. When visiting the
start page, only the bundle for index.js
is loaded.
next/dynamic
For even finer code splitting, Next.js offers the
next/dynamic
function to import components dynamically.
These components are only loaded when they are needed.
import dynamic from 'next/dynamic';
const DynamicComponent = dynamic(() => import('../components/MyComponent'), { ssr: false });
function MyPage() {
return (
<>
<h1>Welcome to my page</h1>
<DynamicComponent />
</>
;
) }
In this example, MyComponent
is only loaded when
MyPage
is rendered.
2 Efficient use of resources: Prevents unnecessary code from loading, optimizing the use of network and browser resources.
3 Better user experience: Faster load times lead to a better user experience and can improve conversion rates and SEO ranking.
While server-side rendering (SSR) works automatically in Next.js,
developers should pay attention to how this affects SSR when using
dynamic import. The { ssr: false }
option in
dynamic
import disables SSR for the component in question,
which can be useful in certain scenarios.
Create a simple Next.js application with two pages: Home
(index.js
) and About (about.js
). Implement the
dynamic loading of a component on the About page to demonstrate the
principles of code splitting.
Basic structure: Create a new Next.js project with two pages: Home and About.
Dynamic component: Create a component
DynamicComponent
and integrate it on the About page. This
component should be loaded dynamically, i.e. only when the About page is
called.
3 Content of the components: - The home page should display a simple text such as “Welcome to the home page”. - The about page should also contain an introductory text and also include the dynamic component.
4 Content of the DynamicComponent
: This
component should contain a text such as “This is a dynamically loaded
component.”
npx create-next-app my-next-project
.pages/index.js
and
pages/about.js
.3 Create dynamic component: - Create a new file
components/DynamicComponent.js
.
4 Implement dynamic loading: - Use
next/dynamic
in pages/about.js
to load
DynamicComponent
dynamically.