Easier management of the lazy loading process

react-with-dynamic

Improved lazy loading in React with suspense and error boundary.

How to Install

First, install the library in your project by npm:

$ npm install react-with-dynamic

Or Yarn:

$ yarn add react-with-dynamic

Getting Started

Without Context configuration

• Use withDynamic:

// App.js

import React from 'react';
import { withDynamic } from 'react-with-dynamic';

const LazyComponent = withDynamic({
  suspenseFallback: <p>Loading...</p>,
  errorBoundaryProps: {
    fallbackComponent: () => <p>Oops! Error occurred!</p>,
    onError: (err) => console.log(err),
  },
})(lazy(() => import('./components/LazyComponent')));

const App = () => {
  return <LazyComponent />;
};

export default App;

With Context configuration

• Set DynamicProvider (if you want to use the same suspense fallback and error boundary config for all lazy components wrapped in withDynamic HOC):

// index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { DynamicProvider } from 'react-with-dynamic';

import App from './App';

ReactDOM.render(
  <DynamicProvider
    suspenseFallback={<p>Loading...</p>}
    errorBoundaryProps={{
      fallbackComponent: () => <p>Oops! Error occurred!</p>,
      onError: (err) => console.log(err),
    }}
  >
    <App />
  </DynamicProvider>,
  document.getElementById('root')
);

• Then use withDynamic:

// App.js

import React from 'react';
import { withDynamic } from 'react-with-dynamic';

const LazyComponent = withDynamic()(
  lazy(() => import('./components/LazyComponent'))
);

const App = () => {
  return <LazyComponent />;
};

export default App;