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.
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.
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:
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.