Code Splitting

Instead of downloading the entire app before users can use it, code splitting allows you to split your code into small chunks which you can then load on demand.

This project setup supports code splitting via dynamic import(). Its proposal is in stage 4. The import() function-like form takes the module name as an argument and returns a Promise which always resolves to the namespace object of the module.

Here is an example:

moduleA.js

  1. const moduleA = 'Hello';
  2. export { moduleA };

App.js

  1. import React, { Component } from 'react';
  2. class App extends Component {
  3. handleClick = () => {
  4. import('./moduleA')
  5. .then(({ moduleA }) => {
  6. // Use moduleA
  7. })
  8. .catch(err => {
  9. // Handle failure
  10. });
  11. };
  12. render() {
  13. return (
  14. <div>
  15. <button onClick={this.handleClick}>Load</button>
  16. </div>
  17. );
  18. }
  19. }
  20. export default App;

This will make moduleA.js and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. For more information on the chunks that are created, see the production build section.

You can also use it with async / await syntax if you prefer it.

With React Router

If you are using React Router check out this tutorial on how to use code splitting with it. You can find the companion GitHub repository here.

Also check out the Code Splitting section in React documentation.