Next.js is all about creating performant web applications. However, the more React components we pull into our MDX via
Prefer to read along as well? Here's the accompanying article.
Instructor: [0:00] When importing these MDX elements to be included within our page dynamically, one thing we might want to pay attention to is the actual performance of our website.
[0:10] Once we have more and more such dynamic components in there, we might want to load them in dynamically, just whenever they are present, because we could totally imagine a situation where we have another article here which does not have a YouTube component.
[0:25] What we can do for that is to use the dynamic import that is offered by Next.js, from next/dynamic. What that allows us -- and let's, for the moment, comment out here that custom link -- is to load this in dynamically.
[0:40] We use that dynamic function, which just doesn't call back, and we then dynamically import our YouTube component from our MDX elements. Once we have those components, we return the Components.YouTube. Obviously, we need to make this async as well. With that, we can then remove the hard-coded import up here.
[1:44] If you want to make high usage of such dynamic imports, we might also think about the strategy of how we want to modularize our MDX elements here. Obviously, if we export all the components from a single MDX elements library here, all of those would be pulled in.
[2:02] In case we want really high dynamic behavior, we might want to split out those components into different libraries or either do deep imports. I normally suggest it to have one single entry point here. You can totally go to your tsconfig.base here.
[2:18] You might want to include another path here and customize it such that everything that comes basically after this path here gets directly pulled out of the src/lib. If you go back to our page component, we can go here now and include the YouTube component directly in here. We can now return this, as we already got the component out of this.
[2:44] If we serve our site again and go back to our website and refresh, we would see the YouTube component still gets pulled in. We also see that dynamic import. We have the YouTube component being pulled in here, but we should not have, for instance, the custom link, which in fact is not present.
[3:03] This allows for a much more fine-grained import based on the configuration of how you set up your tsconfig here.