React Loadable makes lazy loading very easy so that you will need not to worry about downloading a large number of bytes. React Loadable splits your code into chunks so that you only serve required bytes.
First clone my React-Router Boilerplate
git clone firstname.lastname@example.org:saigowthamr/React-router-v4-boilerplate.git reactlazy
npm i // to install dependencies
npm start // to start dev server
I have made a clear separation of header and router config files so that it is easy to read.
App folder structure should be like above image.
Now let’s install ReactLoadable package
npm i --s react-loadable
In our Boilerplate, I have added two routes.
But there is no content in that two routes so that I’m adding now some
dummy content in the app.js file.
Without Lazy Loading there is the single bundle.js file.
Let’s add Lazy loading to our Home route.
For these, I created a lazy.js file in router folder
Now in the lazy.js file, we need to import the react-loadable package and Loading Component.
ReactLoadable function takes options which are loader property and loading
loader: we need to tell the which component you need to load lazily.
loading: Meantime load this loading component So that user does not see the white screen for a long time.
Now lets update router.js.
Let’s see what is happening now when we a load home route. For these, I enabled network throttling.
Have you seen we are now loading in chunks instead of single bundle.js file and meantime we are showing loading component.