Lazy Loading with React

Illustrates how React.Lazy and React.Suspense work.

Since quite a while React ships with some interesting capabilities: Suspense and lazy. Both work hand in hand. Where the React.Suspense component is used a potential fallback will be rendered if a sub-component is still loading / cannot be shown.

The React.Lazy component is the natural counter part that resolves when a promise is resolved. Right now only components (delivered via export default) can be consumed. In the future also general promises / loading procedures may be covered.

The following snippet shows the locality of React.Suspense and introduces how a lazy component may be defined without having modules at hand. This could, obviously, be reused for generically defining a component that lazy loads data.

const LazyHelloComponent = React.lazy(() => new Promise(resolve => setTimeout(() => resolve({
  'default': class extends React.Component {
    render() {
    	return (
      	<div>Hello {this.props.name} yo</div>
      );
    }
  },
}), 5000)));

const LazySideComponent = React.lazy(() => new Promise(resolve => setTimeout(() => resolve({
  'default': class extends React.Component {
    render() {
    	return (
      	<div>Bibop</div>
      );
    }
  },
}), 2000)));

class Hello extends React.Component {
  render() {
    return (
    	<React.Suspense fallback={<div>Loading all</div>}>
        <div>Yo</div>
        <LazySideComponent />
        <React.Suspense fallback={<div>Loading few</div>}>
    	    <LazyHelloComponent name={this.props.name} />
        </React.Suspense>
        <div>Foo</div>
      </React.Suspense>
    );
  }
}

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);
Created .

References

Sharing is caring!