Next.jsQuestion 11 of 15
How do you use a dynamic import to lazy-load a component?
Answer out loud or in your head first, then compare.
Answer
For components you can use next/dynamic, and for a plain module, import(), which returns a Promise.
JSX
'use client';
import dynamic from 'next/dynamic';
import { useState } from 'react';
const Editor = dynamic(() => import('./Editor'), {
loading: () => <p>Loading the editor…</p>,
});
export default function Page() {
const [open, setOpen] = useState(false);
return <>
<button onClick={() => setOpen(true)}>Edit</button>
{open && <Editor />}
</>;
}Pitfall: ssr: false turns off prerendering for that component; I use it on purpose, e.g. for a browser-only library. In the App Router this option belongs in a Client Component, not a Server Component.
How did it go? Be honest — “Not yet” puts the question on your review list.