Code Splitting Libraries & Child Components

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-libraries-child-components/

Libraries and code splitting

Details.js didn’t have to be changed when we added code splitting.

   //    ****        Details.js        ****

 // imagine importing two big libraries
 import _ from 'lodash'
 import moment from 'moment'

Now, when the /details route is accessed, an extra 800kb is loaded.

SearchParams

Does the same for SearchParams.

You can split anywhere, not just routes

In Details.js, you could import Modal lazily, it doesn't have to be a route:

   //    ****        Details.js        ****

  // **** 1. lazily import Modal.  ↴
 const Modal = lazy(() => import('./Modal'))

 ...
 // later we have this:
{showModal ? (
            <Modal>
              <h1>Would you like to adopt {name}?</h1>
              <div className="buttons">
                <button onClick={this.adopt}>Yes</button>
                <button onClick={this.toggleModal}>No</button>
              </div>
            </Modal>
          ) : null}

Basically, he didn't have to modify anything just step 1, use lazy to import Modal.