8

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)

1 Answer 1

10

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;
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

So just to make sure i understand - i can't use Webpack dynamic imports for components? Only for third party libraries, since nothing that comes out of those dynamic imports is renderable?
Correct, You cannot render a promise,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.