Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 898
Gambit2007 Avatar asked Jun 20 '26 19:06

Gambit2007


1 Answers

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;
  }
}
like image 51
felixmosh Avatar answered Jun 23 '26 12:06

felixmosh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!