Dynamic Component Loading (aka Lazy Components)
Even though Next.js can split your app into route-based asynchronously loaded chunks, it is always a good idea to split further if it is needed. The less unnecessary code the user loads up front, the better.
The technique is very simple and completely supported by Next.js:
import dynamic from 'next/dynamic';
And then, anywhere on demand, we can do the loading:
import dynamic from 'next/dynamic' const FooDynamic = dynamic(import('../components/Foo')) export default class Page extends React.Component { state = {show: false}; show = () => this.setState({show: true}); render() { return ( this.state.show ? <FooDynamic/> : <button onClick={this.show}>Show!</button> ); } }
Here, the component will not be loaded until it is actually placed on the page (that is, rendered).
We can even define the dynamic component with a loader:
const loading = () => <div>Loading</div>; const FooDynamicLoader ...