Thursday, 18 January, 2018 UTC


Summary

Developing and building our client-side apps has never been easier. NPM and it’s registry is giving us an access to thousands of thousands of packages. Installing them and attaching to the project is super easy today, but it has one major disadvantage: increasing bundle size.
Why do we care about page speed?
Because we want to deliver the best possible experience to our end users. Doesn’t matter which device they’re using – a smartphone, smartwatch, tablet or desktop computer. The site has to work and has to load quicker than ever – nowadays web users have high expectations!
Code-splitting to the rescue
One of the most popular ways of making our React app load faster is code-splitting. It allows us to load needed parts of the page when they are actually required by the application, not on the initial request. It has a huge impact on the performance by not letting the user download the whole app with vendors at once (we can easily achieve bundle size around ~2mb by adding most common tools and libraries).
One of the methods to split our code is to bundle vendors and the app separately. There is a pattern easily achievable using Webpack – loading code chunks (fragments) for vendors and serve them accordingly to the visited route. That way our end-user doesn’t need to download the whole bundle and is being served with required chunks of the package when they’re really needed.
That’s one way of a code-splitting implementation. What if we split our bundle around the components that actually import specific bundle parts instead of splitting the code around routes at which they are required? That’s the awesome job done by react-loadable.
Getting started
Install the package using npm:
npm i --save react-loadable
or yarn:
yarn add react-loadable

Example code:

The simples example we can make is to create a component which will include another component, wrapped by Loadable, which will automatically make it loaded asynchronously.
import Loadable from 'react-loadable';

const LoadableBlogPostsList = Loadable({
  loader: () => import('../BlogPostsList'),
  loading() {
     return <div>Loading...</div>
  }
});

class Blog extends React.Component {
  render() {
   return (
     <div className="container">
       <h1>My awesome blog</h1>
 
       <h2>Recent posts:</h2>
 
       <BlogPostsList />
     </div>
    );
  }
}

export default Blog;
Useful metrics
  • BundlePhobia – check the cost of adding an NPM package online
  • Import Cost VSCode Extension – pretty handy VSCode extension showing size of the package next to your import statement
  • Webpack Visualizer
Enjoy! Let me know how it goes for you!
The post Getting started with code splitting using react-loadable appeared first on matwrites.com.