Hello Series #1: Dynamic Imports for a Component

Originally Published: 16th September 2018

Thanks to tools like Webpack, we can now dynamically import modules into our code. This is also great for code splitting and reducing the size of our bundles.

This is just a short example using a create-react-app installation and a basic setup of ComponentA and ComponentB.

Example Code

The key action in this example happens in ComponentA by using React’s componentDidMount lifecycle method where you an see I am dynamically importing ComponentB. That being said, this import can be used anywhere when required. You can dynamically require modules after particular events if you so chose.

Image for post
Image for post
Dynamically importing during ComponentA’s lifecycle method componentDidMount.

Here is the full code example of ComponentA dynamically important ComponentB, setting it to local state and then — if that local state variable is not null — rendering it during the render lifecycle method:

Image for post
Image for post
Full example of ComponentA which renders ComponentB after an import.

Original Post: https://www.dennisokeeffe.com/blog/react-dynamic-imports

Hello is a series that is about short, sharp examples. Read more on this series to find small gems to add your toolset.

Senior Engineer @ Culture Amp. Tinkerer and professional self-isolator in 2020.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store