Eric Allen
Interweb Alchemist
Yet.
Yet.
Let's go to the code.
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('../lazy-component'));
export default () => (
<main>
<h1>Lazy Component Below</h1>
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
</main>
);
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => /* webpackChunkName: "lazy" */ import('../lazy-component'));
export default () => (
<main>
<h1>Lazy Component Below</h1>
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
</main>
);
Note: We're going to leave the import statement and variable declaration out out in some later slides due to space constraints.
export default class MyComponent extends Component {
state = {
showLazyComponent: false,
};
render() {
const { showLazyComponent } = this.state;
return (
<main>
<h1>Lazy Component Below</h1>
<button
type="button"
onClick={() => this.setState({ showLazyComponent: !showLazyComponent })}
>
Toggle Lazy
</button>
{showLazyComponent &&
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
}
</main>
);
}
}
import React, { Component, Supsense, lazy } from 'react';
// this will create a new bundle that gets loaded after the current bundle
const lazyComponentPromise = import(/* webpackChunkName: "lazy" */ '../lazy');
const LazyComponent = lazy(() => lazyComponentPromise);
export default () => (
<main>
<h1>Lazy Component Below</h1>
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
</main>
);
import { lazy } from 'react';
export default function lazyWithPreload(componentPromise) => {
const Component = lazy(componentPromise);
Component.preload = componentPromise;
return Component;
};
Note: We'll use this in the next slide.
import React, { Component, Suspense } from 'react';
import lazyWithPreload from '../lazy-with-preload';
const LazyComponent = lazyWithPreload(() => import('../lazy'));
export default class MyComponent extends Component {
state = {
showLazyComponent: false,
};
lazyLoad = () => {
LazyComponent.preload();
this.setState({ showLazyComponent: !this.state.showLazyComponent });
};
render() {
const { showLazyComponent } = this.state;
return (
<main>
<button type="button" onClick={this.lazyLoad}>Toggle Lazy</button>
{this.state.showLazyComponent &&
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
}
</main>
);
}
}
I might have answers.
By Eric Allen
Get to know React.lazy() and when you might want to leverage it. Demos are stored as git tags in this repository: https://github.com/ericrallen/dynamic-import-demo