Code splitting
Code splitting allows the source file to be separated into multiple chunk files. nextjs can fetch all bundles simultaneously and reduce page load time.
Automatic Code Splitting
-
What it is: Next.js automatically splits your code at the page level. Each page you create in the pages/ directory is its own JavaScript bundle.
-
How it works: When a user navigates to a different page, Next.js will only load the JavaScript for that page, not the entire application.
-
Benefit: Reduces the initial bundle size and speeds up the first page load since only the code needed for the initial page is loaded.
Dynamic import
Dynamic import differs from absolute and relative import in that we can take advantage of importing components or external modules at the time of requirement, not in the initial rendering itself.
By default dynamic components render on the server side.
import dynamic from 'next/dynamic'
const Settings = dynamic(()=>import("../components/settings"))
function Home()
{
return <>
<Settings/>
<div>home</div>
</>
}
export default home
Client-side rendering (SSR: false)
Next.js allows you to disable server-side rendering for code-split components. This can be useful for components that are not needed during the initial page load. You can also provide a loading placeholder to enhance user experience while the dynamic component is being rendered.
import dynamic from 'next/dynamic'
const Settings = dynamic(()=>import("../components/settings"), {
ssr: false,
loading: () => <div>Loading client-only component...</div>
})
function Home()
{
return <>
<Settings/>
<div>home</div>
</>
}
export default home
Conditional Dynamic Imports
If we need to exclude specific dynamically imported chunk from the initial bundle, we have to add a render condition:
const Settings = dynamic(() => import("../components/settings"))
function Home() {
const [showSettings, setShowSettings] = useState(false)
return (
<>
{showSettings && <Settings />}
<button onClick={() => setShowSettings(true)}>Show Settings</button>
<div>home</div>
</>
)
}
In this example, the Settings component will only be loaded when the user clicks the button. This is particularly useful for:
- Modal windows
- Complex forms that aren't immediately visible
- Features that only certain users might access
Conclusion
Use dynamic imports if you have heavy resource components that don’t need to render on page load. Dynamic imports can greatly impact page load times with minimal effort.