[React] Lazy loading module

To understand lazy loading in React, we need to think in two steps.

 

1. Use dynamice import: to load script

2. Use React.lazy to load dynammice import, it will hook up with a component

const loadGlobe = () => import('../globe')
const Globe = React.lazy(loadGlobe)

 

Define like this is good because we can do prefetching by dynamice import. And only when the component by using React.lazy.

// Code splitting
// http://localhost:3000/isolated/exercise/01.js

import React, {useEffect} from 'react'
// 🐨 use React.lazy to create a Globe component which using a dynamic import
// to get the Globe component from the '../globe' module.

const loadGlobe = () => import('../globe')
const Globe = React.lazy(loadGlobe)

function App() {
  const [showGlobe, setShowGlobe] = React.useState(false)

  // 🐨 wrap the code below in a <React.Suspense /> component
  // with a fallback.
  // 💰 try putting it in a few different places and observe how that
  // impacts the user experience.
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        flexDirection: 'column',
        justifyContent: 'center',
        height: '100%',
        padding: '2rem',
      }}
    >
      <label style={{marginBottom: '1rem'}}>
        <input
          type="checkbox"
          checked={showGlobe}
          onMouseEnter={e => loadGlobe()}
          onChange={e => setShowGlobe(e.target.checked)}
        />
        {' show globe'}
      </label>
      <div style={{width: 400, height: 400}}>
        {showGlobe ? (
          <React.Suspense fallback={<div>Loading Map...</div>}>
            <Globe />
          </React.Suspense>
        ) : null}
      </div>
    </div>
  )
}
// 🦉 Note that if you're not on the isolated page, then you'll notice that this
// app actually already has a React.Suspense component higher up in the tree
// where this component is rendered, so you *could* just rely on that one.

export default App

 

Prefetch by webpack:

const loadGlobe = () => import(/* webpackPrefetch: true */ '../globe') // then you don't need to do egar loading anymore
      <label style={{marginBottom: '1rem'}}>
        <input
          type="checkbox"
          checked={showGlobe}
          onChange={e => setShowGlobe(e.target.checked)}
        />
        {' show globe'}
      </label>
      <div style={{width: 400, height: 400}}>
        {showGlobe ? (
          <React.Suspense fallback={<div>Loading Map...</div>}>
            <Globe />
          </React.Suspense>
        ) : null}
      </div>

Webpack will add those scripts into head.

posted @ 2020-10-22 00:06  Zhentiw  阅读(111)  评论(0)    收藏  举报