Hello Series #1: Dynamic Imports for a Component

Dennis O'Keeffe
2 min readSep 23, 2018

--

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.

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:

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.

--

--

Dennis O'Keeffe
Dennis O'Keeffe

No responses yet