Code Splitting Routes

In notebook:
FrontEndMasters Intermediate React
Created at:
2019-06-24
Updated:
2019-08-15
Tags:
React libraries JavaScript Performance

https://frontendmasters.com/courses/intermediate-react-v2/code-splitting-routes/

Code Splitting

Resets the GIT repo to original state.

The idea is that you only load what's essential for the page you are visiting.

For example, the Details page's code, doesn't need on the home page and can be deferred.

   //    ****        App.js        ****

 // **** 1. import lazy, and Suspense  ↴
import React, { useState, lazy, Suspense } from "react";
import ReactDOM from "react-dom";
import { Router, Link } from "@reach/router";
 // **** 2. remove Details.js.  ↴
 // import Details from './Details'
 // import SearchParams from './SearchParams'
import ThemeContext from "./ThemeContext";

 // **** 3. add Details import config.  ↴
 // NOTE, that this is ESModules dynamic import
 // it's Parcel that does the code splitting
const Details = lazy(() => import("./Details"));
const SearchParams = lazy(() => import("./SearchParams"));

const App = () => {
  const theme = useState("darkblue");
  return (
    <ThemeContext.Provider value={theme}>
      <div>
        <header>
          <Link to="/">Adopt Me!</Link>
        </header>
         // **** 4. add the Suspense component.  ↴
         // need to give it a fallback attribute
         // when the code is not ready yet
        <Suspense fallback={<h1>loading route …</h1>}>
          <Router>
            <SearchParams path="/" />
            <Details path="/details/:id" />
          </Router>
        </Suspense>
      </div>
    </ThemeContext.Provider>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

If you are doing code splitting, then you should split at least 30Kb+ components.