React Universal Loader

Do you think that React.Lazy is only for lazy loading components? Think again. You can actually lazy load any kind of thing.

Creating components on the fly is super simple with React. After all, a component is just a function. Creating functions when we need them was always easy and straight forward with JS. So is creating components.

Initially, React.lazy was thought of as an ideal way of lazy loading components coming from lazy loaded (i.e., separately bundled) modules. But actually the API is more friendly than it seems. Let's think about it again: All it takes is a function that returns a Promise resolving in a { default: ComponentType } shaped object. Naturally, this was picked in such a way to be super friendly to modules (using a default export), however, nothing prevents us from using this differently.

Simple example:

const App = React.lazy(() => new Promise(resolve => setTimeout(() => {
  resolve({
    default: () => (
      <div>
        <b>Nice magic trick!</b>
      </div>
    ),
  });
}, 5000)));

const app = (
  <React.Suspense fallback={<div>Loading...</div>}>
    <App />
  </React.Suspense>
);

Here we load the component with the custom promise resolved after a timeout of 5 seconds.

Created .

References

Sharing is caring!