💡 React Code Splitting in 2019
Tags: react, javascript, ssr, codesplitting
Published: 2019-03-19 12:23:29

---
title: 💡 React Code Splitting in 2019
published: true
description: React.lazy? Loadable-Components? SSR? CSS? What next?
tags: react, javascript, ssr, code splitting
cover_image: https://habrastorage.org/webt/da/lx/0b/dalx0bnbenxiqebdymmcrp8in68.png
series: A split second later 
---
It's 2019! Everybody thinks they know code splitting. So - let's double check!
![](https://habrastorage.org/webt/da/lx/0b/dalx0bnbenxiqebdymmcrp8in68.png)
## What does code-splitting stand for?
In short – code-splitting is just about not loading a whole thing. Then you are reading this page you don't have to load a whole site. When you are selecting a single row from a database – you don't have to take all. 
Obvious? Code splitting is also quite obvious, just not about your data, but your code.
<cut />
## Who is making code-splitting?
`React.lazy`? No – it only uses it. Code-splitting is working on a bundler level – webpack, parcel, or just your file system in case of "native" `esm modules`. Code splitting is just files, files you can load somewhere "later".

## Who is using code splitting?
`React.lazy` is using. Just using code splitting of your bundler. Just calling import when got rendered. And that's all.

## What's about React-loadable?
`React.lazy` superseded it. And have provided more features, like `Suspense` to control loading state. So - use `React.Lazy` instead. 

> Yep, that's all. Thank you for reading and have a nice day.


## Why this article is not finished?
Well. There are a few _grey zones_ about `React.lazy` and code splitting I forgot to mention.

###Grey Zone 1 – testing
It's not easy to test `React.lazy` due to its _asynchroniosity_. It would be just "empty", as long as it is not loaded yet(even if it is) – `Promises` and `import` returns, and lazy accepts, __promises__, which always got executed in the __next tick__.

It’s not easy to test `React.lazy` due to its asynchronous nature. The result of `mount(MyLazyComponent)` would be just “empty”, as long as the “real” `Component`, _behind_ `MyLazy`, is not loaded yet. And even if it is – `import` returns, and `lazy` accepts, __promises__, which always got executed in the __next tick__. So — you will never get Component in the __current tick__. It’s the law!
```js
const LazyComponent = lazy(() => import('/path/to/dynamic/component'));
const Fallback = () => <div />;
const SuspenseComponent = () => (
    <Suspense fallback={<Fallback />}>
      <LazyComponent />
    </Suspense>
);
const wrapper = mount(<SuspenseComponent />)
expect(wrapper.find('Fallback')).to.have.lengthOf(1)
expect(wrapper.find('DynamicComponent')).to.have.lengthOf(0)
// ^ not loaded

await wrapper.waitUntilLazyLoaded()
// ^ Oh god, why!?

expect(wrapper.find('Fallback')).to.have.lengthOf(0)
expect(wrapper.find('DynamicComponent')).to.have.lengthOf(1)
// ^ loaded!
```

Proposed solution? You would not believe it, but the proposed solution is to use synchronous _thenables_.
{% github https://github.com/facebook/react/pull/14626 %}
So - let's make out import SYNCHRONOUS!!
```js
const LazyText = lazy(() => ({
   then(cb) {   
      cb({default: Text});
      // this is "sync" thenable
   },
}));     
const root = ReactTestRenderer.create(
  <Suspense fallback={<Text text="Loading..." />}>          
     <LazyText text="Hi" /> // this lazy is not very lazy
  </Suspense>,
);
```
It's not hard to convert import function to a memoized synchronous thenable.
```js
const syncImport = (importFn) => {
   let preloaded = undefined;
   const promise = importFn().then(module => preloaded = module);
   // ^ "auto" import and "cache" promise   
   return () => preloaded ? { then: () => preloaded } : promise;
   // ^ return sync thenable then possible
}
const lazyImport = isNode ? syncImport : a => a; 
// ^ sync for node, async for browser
const LazyComponent = React.lazy(lazyImport(() => import('./file'));
```

### Grey zone 2 – SSR
> If you DON'T need SSR – please continue reading the article!

`React.lazy` is SSR friendly. But it requires `Suspense` to work, and Suspense is __NOT server-side friendly__.

There are 2 solutions:

- Replace Suspense with Fragment, via mocking for example. Then, use the altered version of `import` with synchronous `then` to make lazy also behave synchronously.
```js
import React from 'react';
const realLazy = React.lazy;
React.lazy = importer => realLazy(syncImport(importer));
React.Suspense = React.Fragment; // :P
// ^ React SSR just got fixed :D
```

This is a good option, but it wouldn't be quite client-side friendly. Why? Let's define the 2nd possible solution:
- Use a __specialised library__ to track used scripts, chunks and styles, and load them on client-side (especially styles!) before React hydration. Or else – you would render empty holes instead of your code split components. Yet again – you didn't load the code you just split, so you can't render anything you are going to.

### Behold code-splitting libraries
- [Universal-component](https://www.npmjs.com/package/react-universal-component) – the oldest, and still maintainable library. It "invented" code splitting in terms of – taught Webpack to code split.
- [React-loadable](https://www.npmjs.com/package/react-loadable) – very popular, but unmaintained library. Made code spitting a popular thing. Issues are closed, so there is no community around.
- [Loadable-components](https://www.npmjs.com/package/@loadable/component) – a feature-complete library, it's a pleasure to use, with the most active community around.
- [Imported-component](https://www.npmjs.com/package/react-imported-component) – a single library, not bound to Webpack, ie capable to handle parcel or esm.
- [React-async-component](https://github.com/ctrlplusb/react-async-component) – already dead library(yet popular), which made a significant impact on everything around code-splitting, custom React tree traversal and SSR.
- _Another library – there were many libraries, many of which did not survive Webpack evolution or React 16 – I haven't listed them here, but if you know a good candidate – just DM me._

### Which library to pick?
It's easy – __not react-loadable__ – it's heavy unmaintained and obsolete, even if it is still mega popular. (and thank you for popularizing code-splitting, yet again)

_Loadable-components_ – might be a very good choice. It is very well written, actively maintained and support everything out of the box. Support "full dynamic imports", allowing you to import files depending on the props given, but thus untypable. Supports Suspense, so could replace React.lazy.


_Universal-component_ – actually "inventors" of full dynamic imports – they implemented it in Webpack. And many other things at low-level – they did it. I would say – this library is a bit hardcore, and a bit less user friendly. Loadable-components documentation is unbeatable. It's worth if not to use this library, then read documentation - there are so many details you should know…



_React-imported-component_ – is a bit odd. It's bundler independent, so it would never break (there is nothing to break), would work with Webpack 5 and 55, but that comes with a cost. While previous libraries during SSR would add all the used scripts to the page body, and you will be able to load all the scripts in a parallel – imported don't know files names, and will call the original "imports"(that's why bundle independent) to load used chunks, but able to make calls only from inside the main bundle – so all additional scripts would be loaded only after the main one got downloaded and executed. Does not support full dynamic imports, like React.lazy, and, as a result – typeable. Also supports Suspense. Uses synchronous _thenables_ on SSR. It also has an absolutely different approach for CSS, and perfect stream rendering support.


There is no difference in quality or popularity between listed libraries, and we are all good friends – so pick by your heart.

{% github https://github.com/smooth-code/loadable-components %}
{% github https://github.com/theKashey/react-imported-component %}
{% github https://github.com/faceyspacey/react-universal-component %}

## Grey zone 3 – hybrid render
SSR is a good thing, but, you know, hard. Small projects might want to have a SSR – there are a lot of reasons to have it –but they might not want to setup and maintain it.

> SSR could be really, REALLY hard. Try `razzle` or go with `Next.js` if you want a quick win.

So the easiest my solution for SSR, especially for simple SPA would be prerendering. Like opening your SPA in a browser and hitting "Save" button. Like:
- [React-snap](https://github.com/stereobooster/react-snap) - uses [puppeteer](https://github.com/GoogleChrome/puppeteer)(aka headless Chrome) to render your page in a "browser" and saves a result as a static HTML page.
- [Rendertron](https://github.com/GoogleChrome/rendertron) - which does the same, but in a different (_cloud_) way.

Prerendering is "SSR" without "Server". It's SSR using a Client. Magic! And working out of the box… … … but not for code-spitting.
So - you just rendered your page in a browser, saved HTML, and asked to load the same stuff. But Server Side Specific Code (to collect all used chunks) was not used, cos __THERE IS NO SERVER__!

![](https://habrastorage.org/webt/tr/sz/9i/trsz9i4ct8jc7cnwxtm-ljnepuq.png)

In the previous part, I've pointed to libraries which are bound to webpack in terms of collecting information about used chunks - they could not handle hybrid render at all.
> Loadable-components version 2(incompatible with current version 5), was partially supported by react-snap. Support has gone.

React-imported-component could handle this case, as long as it is not bound to the bundler/side, so there is no difference for SSR or Hybrid, but only for `react-snap`, as long as it supports "state hydration", while `rendertron` does not.
> This ability of react-imported-component was found while writing this article, it was not known before - see [example](https://github.com/theKashey/react-imported-component/tree/master/examples/hybrid/react-snap). It's quite easy.

And here you have to use another solution, which is just perpendicular to all other libraries.

### React-prerendered-component
This library was created for partial hydration, and could partially rehydrate your app, keeping the rest still de-hydrated. And it works for SSR and Hybrid renderers without any difference.
The idea is simple:
- during SSR - render the component, wrapped with a <div/>
- on the client - find that div, and use innerHTML until Component is ready to replace dead HTML.
- you don't have to load, and wait for a chunk with split component to _NOT render a white hole instead of it_ - just use pre-rendered HTML, which is absolutely equal to the one _a real component_ would render, and which already exists - it comes with a server(or hybrid) response .

> That's why we have to wait for all the chunks to load before hydrate - to __match__ server-rendered HTML. That's why we could use pieces of server-rendered HTML until the ​client is not ready - it is equal to the one we are only going to produce.

```js
import {PrerenderedComponent} from 'react-prerendered-component';
const importer = memoizeOne(() => import('./Component'));
// ^ it's very important to keep the "one" promise
const Component = React.lazy(importer); 
// or use any other library with ".prefetch" support
// all libraries has it (more or less)
const App = () => (
  <PrerenderedComponent live={importer()}> 
   {/* ^ shall return the same promise */ }
      <Component /> 
   {/* ^ would be rendered when component goes "live" */ }
  </PrerenderedComponent>
);
```
{% github https://github.com/theKashey/react-prerendered-component %}

### TLDR?
- don't use react-loadable, it would not add any valuable value
- React.lazy is good, but too simple, yet.
- SSR is a hard thing, and you should know it
- Hybrid puppeteer-driven rendering is a thing. Sometimes even harder thing.