Last active
February 27, 2020 07:13
-
-
Save hrc7505/9fec9602d762c382b27ebd210cc2e201 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example taken from the official ReactJs docs | |
import("./math").then(math => { | |
console.log(math.add(16, 26)); | |
}); | |
/*************************/ | |
// Without lazy loading | |
import AnyComponent from './AnyComponent'; | |
// With lazy loading | |
const AnyComponent= React.lazy(() => import('./AnyComponent')); | |
/*************************/ | |
// Use of lazy(), Suspense and Suspense fallback prop | |
const AnyComponent = React.lazy(() => import('./AnyComponent')); | |
function LazyComponent() { | |
return ( | |
<Suspense fallback={<div>Loading...</div>}> | |
<AnyComponent/> | |
</Suspense> | |
); | |
} | |
/*************************/ | |
// Lazy loading of multiple components with same Suspense | |
const AnyComponent = React.lazy(() => import('./AnyComponent')); | |
const NewComponent = React.lazy(() => import('./NewComponent')); | |
function LazyComponent() { | |
return ( | |
<Suspense fallback={<div>Loading...</div>}> | |
<AnyComponent/> | |
<NewComponent/> | |
</Suspense> | |
); | |
} | |
/*************************/ | |
// Route based code splitting | |
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; | |
import React, { Suspense, lazy } from 'react'; | |
import Spinner from "./Spinner"; | |
const Dashboard = lazy(() => import('./Dashboard')); | |
const Contact = lazy(() => import('./Contact')); | |
const App = () => ( | |
<Router> | |
<Suspense fallback={<Spinner/>}> | |
<Switch> | |
<Route exact path="/" component={Dashboard}/> | |
<Route path="/contact" component={Contact}/> | |
</Switch> | |
</Suspense> | |
</Router> | |
); | |
/*************************/ | |
// Lazy loading for non-default exports | |
// AnyComponent.js | |
export { AnyComponent as default } from "./ManyComponents.js"; | |
// App.js | |
const AnyComponent= lazy(() => import("./AnyComponent.js")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment