Skip to content

Instantly share code, notes, and snippets.

@hrc7505
Last active February 27, 2020 07:13
Show Gist options
  • Save hrc7505/9fec9602d762c382b27ebd210cc2e201 to your computer and use it in GitHub Desktop.
Save hrc7505/9fec9602d762c382b27ebd210cc2e201 to your computer and use it in GitHub Desktop.
// 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