React Loadable
See original GitHub issueimport()
is great for code splitting, but it’s not enough to use in your app on it’s own.
React Loadable provides the rest for any React app:
- Loading states
- Error states
- Avoids “Flash Of Loading State”
- Timeouts
- Loading multiple resources in parallel
- Preloading
But the biggest problem is with server-side rendering.
When you use an app with nested asynchronously loaded components, it creates this waterfall effect. One component loads to render it’s children where one of the children loads another component which loads another component and so on.
This forces you to be annoyingly careful with which component you allow to load async.
React Loadable manages to use server-side rendering in order to avoid this waterfall. It preloads all of your components server-side and as it renders them it makes sure to send down the relevant <script>
and <link>
tags.
I know that Create React App doesn’t do any kind of server-side rendering (yet?), but React Loadable is a really great default for the ecosystem but I would like to see what it would look like if we set up a client-side portion for CRA users.
Right now the way I have people set it up looks like this:
// src/entry.js
import React from 'react';
import ReactDOM from 'react-dom';
import Loadable from 'react-loadable';
import App from './components/App';
window.main = () => {
Loadable.preloadReady().then(() => {
ReactDOM.hydrate(<App/>, document.getElementById('app'));
});
};
<script src="/dist/main.js"></script>
...
<script>window.main();</script>
</body>
</html>
That way we can trigger our code to run after all the other necessary bundles are in place, which makes for a seamless transition when doing server-side rendering.
Using React Loadable like this allows you to place hundreds of dynamically loaded components all over your app without slowing down the startup experience with loading screens and speeding it up by not needing to load nearly as much code.
Is there something that we can put in Create React App that makes it easier to setup React Loadable or similar tools?
Issue Analytics
- State:
- Created 6 years ago
- Reactions:11
- Comments:11 (4 by maintainers)
Top GitHub Comments
I wonder how often people add SSR to CRA projects, as opposed to starting from a SSR-specific boilerplate or something like Next.js. Not sure how we can get data on that.
React Loadable can be used with CRA with named imports:
This will produce the following output in the manifest file
asset-manifest.json
:and, on the server, the
Loadable.Capture
will get the following:From here, it’s just a matter of mapping this to the entries in the manifest file:
Everything else works as described in the docs: https://github.com/thejameskyle/react-loadable#preloading-all-your-loadable-components-on-the-server, BUT without the need of the extra webpack plugin.