Gambit2007
Gambit2007

Reputation: 4006

Using React.lazy vs. webpack dynamic imports?

I was wondering what the difference is between "declaring" dynamic imports using React.lazy() like:

const Component = React.lazy(() => import('./Component'));

Or doing it using webpack's dynamic imports like explained here: https://webpack.js.org/guides/code-splitting/#dynamic-imports

(In my case, i'm planning on doing the bundling in webpack anyway)

Upvotes: 8

Views: 6550

Answers (1)

felixmosh
felixmosh

Reputation: 35573

React.lazy gets a callback which returns a Promise, and returns a renderable component.

Webpacks dynamic imports returns a Promise which will be resolved when the chunk is loaded, therefore, you can't directly render it.

You can reimplement what React.lazy does, this is really basic implementation.

class SomeComponent extends React.Component {
  state = {LazyComponent: null};

  async componentDidMount() {
    const LazyComponent = await import('./path/to/LazyComponent');
    this.setState({LazyComponent});
  }
  render() {
    const {LazyComponent} = this.state;
    return LazyComponent ? <LazyComponent {...props} /> : null;
  }
}

Upvotes: 10

Related Questions