If your company or project is using React Loadable, please open a PR and add
yourself to this list (in alphabetical order please)
Also See:
react-loadable-visibility - Building on top of and keeping the same API as react-loadable, this library enables you to load content that is visible on the screen.
Guide
So you've got your React app, you're bundling it with Webpack, and things are
going smooth. But then one day you notice your app's bundle is getting so big
that it's slowing things down.
It's time to start code-splitting your app!
Code-splitting is the process of taking one large bundle containing your entire
app, and splitting them up into multiple smaller bundles which contain separate
parts of your app.
This might seem difficult to do, but tools like Webpack have this built in, and
React Loadable is designed to make it super simple.
Route-based splitting vs. Component-based splitting
A common piece of advice you will see is to break your app into separate routes
and load each one asynchronously. This seems to work well enough for many apps–
as a user, clicking a link and waiting for a page to load is a familiar
experience on the web.
But we can do better than that.
Using most routing tools for React, a route is simply a component. There's
nothing particularly special about them (Sorry Ryan and Michael– you're what's
special). So what if we optimized for splitting around components instead of
routes? What would that get us?
As it turns out: Quite a lot. There are many more places than just routes where
you can pretty easily split apart your app. Modals, tabs, and many more UI
components hide content until the user has done something to reveal it.
Example: Maybe your app has a map buried inside of a tab component. Why
would you load a massive mapping library for the parent route every time when
the user may never go to that tab?
Not to mention all the places where you can defer loading content until higher
priority content is finished loading. That component at the bottom of your page
which loads a bunch of libraries: Why should that be loaded at the same time as
the content at the top?
And because routes are just components, we can still easily code-split at the
route level.
Introducing new code-splitting points in your app should be so easy that you
don't think twice about it. It should be a matter of changing a few lines of
code and everything else should be automated.
Introducing React Loadable
React Loadable is a small library that makes component-centric code splitting
incredibly easy in React.
Loadable is a higher-order component (a function that creates a component)
which lets you dynamically load any module before rendering it into your app.
Let's imagine two components, one that imports and renders another.
import Bar from './components/Bar';class Foo extends React.Component { render() { return <Bar/>; }}
Right now we're depending on Bar being imported synchronously via import,
but we don't need it until we go to render it. So why don't we just defer that?
When you use import() with Webpack 2+, it will
automatically code-split for
you with no additional configuration.
This means that you can easily experiment with new code splitting points just
by switching to import() and using React Loadable. Figure out what performs
best for your app.
Creating a great "Loading..." Component
Rendering a static "Loading..." doesn't communicate enough to the user. You
also need to think about error states, timeouts, and making it a nice
experience.
To make this all nice, your loading component receives a
couple different props.
Loading error states
When your loader fails, your loading component
will receive an error prop which will be an Error object (otherwise it
will be null).
function Loading(props) { if (props.error) { return <div>Error! <button onClick={ props.retry }>Retry</button></div>; } else { return <div>Loading...</div>; }}
Avoiding Flash Of Loading Component
Sometimes components load really quickly (<200ms) and the loading screen only
quickly flashes on the screen.
A number of user studies have proven that this causes users to perceive things
taking longer than they really have. If you don't show anything, users perceive
it as being faster.
So your loading component will also get a pastDelay prop
which will only be true once the component has taken longer to load than a set
delay.
function Loading(props) { if (props.error) { return <div>Error! <button onClick={ props.retry }>Retry</button></div>; } else if (props.pastDelay) { return <div>Loading...</div>; } else { return null; }}
This delay defaults to 200ms but you can also customize the
delay in Loadable.
Sometimes network connections suck and never resolve or fail, they just hang
there forever. This sucks for the user because they won't know if it should
always take this long, or if they should try refreshing.
Technically you can do whatever you want within loader() as long as it
returns a promise and you're able to render something.
But writing it out can be a bit annoying.
To make it easier to load multiple resources in parallel, you can use
Loadable.Map.
Loadable.Map({ loader: { Bar: () => import('./Bar'), i18n: () => fetch('./i18n/bar.json').then(res => res.json()), }, render(loaded, props) { let Bar = loaded.Bar.default; let i18n = loaded.i18n; return <Bar {...props} i18n={i18n}/>; },});
When using Loadable.Map the render() method is required. It
will be passed a loaded param which will be an object matching the shape of
your loader.
Preloading
As an optimization, you can also decide to preload a component before it gets
rendered.
For example, if you need to load a new component when a button gets pressed,
you could start preloading the component when the user hovers over the button.
The component created by Loadable exposes a
static preload method which does exactly this.
import express from 'express';import React from 'react';import ReactDOMServer from 'react-dom/server';import App from './components/App';const app = express();app.get('/', (req, res) => { res.send(` <!doctype html> <html lang="en"> <head>...</head> <body> <div id="app">${ReactDOMServer.renderToString(<App/>)}</div> <script src="/dist/main.js"></script> </body> </html> `);});app.listen(3000, () => { console.log('Running on http://localhost:3000/');});
Preloading all your loadable components on the server
The first step to rendering the correct content from the server is to make sure
that all of your loadable components are already loaded when you go to render
them.
To do this, you can use the Loadable.preloadAll
method. It returns a promise that will resolve when all your loadable
components are ready.
But don't worry too much about these options. React Loadable includes a
Babel plugin to add them for you.
Just add the react-loadable/babel plugin to your Babel config:
{ "plugins": [ "react-loadable/babel" ]}
Now these options will automatically be provided.
Finding out which dynamic modules were rendered
Next we need to find out which modules were actually rendered when a request
comes in.
For this, there is Loadable.Capture component which can
be used to collect all the modules that were rendered.
import Loadable from 'react-loadable';app.get('/', (req, res) => { let modules = []; let html = ReactDOMServer.renderToString( <Loadable.Capture report={moduleName => modules.push(moduleName)}> <App/> </Loadable.Capture> ); console.log(modules); res.send(`...${html}...`);});
Mapping loaded modules to bundles
In order to make sure that the client loads all the modules that were rendered
server-side, we'll need to map them to the bundles that Webpack created.
This comes in two parts.
First we need Webpack to tell us which bundles each module lives inside. For
this there is the React Loadable Webpack plugin.
Import the ReactLoadablePlugin from react-loadable/webpack and include it
in your webpack config. Pass it a filename for where to store the JSON data
about our bundles.
// webpack.config.jsimport { ReactLoadablePlugin } from 'react-loadable/webpack';export default { plugins: [ new ReactLoadablePlugin({ filename: './dist/react-loadable.json', }), ],};
Then we'll go back to our server and use this data to convert our modules to
bundles.
To convert from modules to bundles, import the getBundles
method from react-loadable/webpack and the data from Webpack.
import Loadable from 'react-loadable';import { getBundles } from 'react-loadable/webpack'import stats from './dist/react-loadable.json';app.get('/', (req, res) => { let modules = []; let html = ReactDOMServer.renderToString( <Loadable.Capture report={moduleName => modules.push(moduleName)}> <App/> </Loadable.Capture> ); let bundles = getBundles(stats, modules); // ...});
We can then render these bundles into <script> tags in our HTML.
It is important that the bundles are included before the main bundle, so that
they can be loaded by the browser prior to the app rendering.
However, as the Webpack manifest (including the logic for parsing bundles) lives in
the main bundle, it will need to be extracted into its own chunk.
Notice: As of Webpack 4 the CommonsChunkPlugin has been removed and the manifest doesn't need to be extracted anymore.
let bundles = getBundles(stats, modules);res.send(` <!doctype html> <html lang="en"> <head>...</head> <body> <div id="app">${html}</div> <script src="/dist/manifest.js"></script> ${bundles.map(bundle => { return `<script src="/dist/${bundle.file}"></script>` // alternatively if you are using publicPath option in webpack config // you can use the publicPath value from bundle, e.g: // return `<script src="${bundle.publicPath}"></script>` }).join('\n')} <script src="/dist/main.js"></script> </body> </html>`);
Preloading ready loadable components on the client
We can use the Loadable.preloadReady() method on the
client to preload the loadable components that were included on the page.
Like Loadable.preloadAll(), it returns a promise,
which on resolution means that we can hydrate our app.
// src/entry.jsimport React from 'react';import ReactDOM from 'react-dom';import Loadable from 'react-loadable';import App from './components/App';Loadable.preloadReady().then(() => { ReactDOM.hydrate(<App/>, document.getElementById('app'));});
Now server-side rendering should work perfectly!
API Docs
Loadable
A higher-order component for dynamically loading a module before
rendering it, a loading component is rendered
while the module is unavailable.
function LoadingComponent(props) { if (props.error) { // When the loader has errored return <div>Error! <button onClick={ props.retry }>Retry</button></div>; } else if (props.timedOut) { // When the loader has taken longer than the timeout return <div>Taking a long time... <button onClick={ props.retry }>Retry</button></div>; } else if (props.pastDelay) { // When the loader has taken longer than the delay return <div>Loading...</div>; } else { // When the loader has just started return null; }}Loading({ loading: LoadingComponent,});
This will call all of the
LoadableComponent.preload methods recursively
until they are all resolved. Allowing you to preload all of your dynamic
modules in environments like the server.
It's important to note that this requires that you declare all of your loadable
components when modules are initialized rather than when your app is being
rendered.
In order to send the right bundles down
when rendering server-side, you'll need the React Loadable Webpack plugin
to provide you with a mapping of modules to bundles.
// webpack.config.jsimport { ReactLoadablePlugin } from 'react-loadable/webpack';export default { plugins: [ new ReactLoadablePlugin({ filename: './dist/react-loadable.json', }), ],};
This will create a file (opts.filename) which you can import to map modules
to bundles.
Specifying the same loading component or delay every time you use
Loadable() gets repetitive fast. Instead you can wrap Loadable with your
own Higher-Order Component (HOC) to set default options.
import Loadable from 'react-loadable';import Loading from './my-loading-component';export default function MyLoadable(opts) { return Loadable(Object.assign({ loading: Loading, delay: 200, timeout: 10000, }, opts));};
Then you can just specify a loader when you go to use it.
Unfortunately at the moment using wrapped Loadable breaks react-loadable/babel so in such case you have to add required properties (modules, webpack) manually.