UNPKG

react-with-dynamic

Version:

Improved lazy loading in React with suspense and error boundary

111 lines (77 loc) 2.8 kB
# [react-with-dynamic](https://github.com/JB1905/react-with-dynamic) (WIP) [![NPM version](https://img.shields.io/npm/v/react-with-dynamic?style=flat-square)](https://www.npmjs.com/package/react-with-dynamic) [![NPM downloads](https://img.shields.io/npm/dm/react-with-dynamic?style=flat-square)](https://www.npmjs.com/package/react-with-dynamic) [![NPM license](https://img.shields.io/npm/l/react-with-dynamic?style=flat-square)](https://www.npmjs.com/package/react-with-dynamic) [![Codecov](https://img.shields.io/codecov/c/github/JB1905/react-with-dynamic?style=flat-square)](https://codecov.io/gh/JB1905/react-with-dynamic) [![Travis](https://img.shields.io/travis/com/JB1905/react-with-dynamic/master?style=flat-square)](https://travis-ci.com/JB1905/react-with-dynamic) [![Bundle size](https://img.shields.io/bundlephobia/min/react-with-dynamic?style=flat-square)](https://bundlephobia.com/result?p=react-with-dynamic) ## About Improved lazy loading in React with suspense and error boundary ## Demo - [Basic](https://codesandbox.io/s/basic-demo-4oiuf) - [With Context](https://codesandbox.io/s/context-demo-5n20l) ## How to Install First, install the library in your project by npm: ```sh $ npm install react-with-dynamic ``` Or Yarn: ```sh $ yarn add react-with-dynamic ``` ## Getting Started ### Without Context configuration **• Use withDynamic:** ```js // App.js import React from 'react'; import { withDynamic } from 'react-with-dynamic'; const LazyComponent = withDynamic({ suspenseFallback: <p>Loading...</p>, errorBoundaryProps: { fallback: <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):** ```js // 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={{ fallback: <p>Oops! Error occurred!</p>, onError: (err) => console.log(err), }} > <App /> </DynamicProvider>, document.getElementById('root') ); ``` **• Then use withDynamic:** ```js // 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; ``` ## License This project is licensed under the MIT License © 2021-present Jakub Biesiada