React Loadable is used for Splitting the Code by Components and Routes. HOW?
Code splitting is a technique which is being used with modern web app development that allows to load chunks of code only when needed. These days we are creating more complex web apps. Challenge these days is not about the designs or style. Target is the performance, we have a multiple ways to improve the performance of the web app. One of which is using React Loadable for splitting the code.
What this code splitting means??? So, let’s suppose we have 2 pages. One is Home page and other is About. This is an example to explain what is code splitting and why this is used. So if we are in Home page then we definitely don’t need the data i.e. code of the About page. So we can split the code on the basis of route here. So when /home route is hit, we have code of home page only and when /about route is hit we have About page code. So, this makes loading of the pages faster since it has to fetch specific code.
Now, how we use React-Loadable?? So, we wrap the components using react loadable and create high order components.
Install
$ npm i react-loadable
# or
$ yarn add react-loadable
Usage
import Loadable from 'react-loadable';
import Loading from './my-loading-component';
const LoadableComponent = Loadable({
loader: () => import('./my-component'),
loading: Loading,
});
export default class App extends React.Component {
render() {
return <LoadableComponent/>;
}
}
The Loadable higher-order component takes an object with two keys: loader and loading:
- loader: Expects a function that returns a promise that resolves to a React component. Dynamic imports using
import()return a promise, so all we have to do is point to the location of the component to load. - loading: Expects a component to render while the code is being loaded.
Easy Demonstration explaining Loadable.
https://codesandbox.io/s/react-loadable-03joz?file=/src/App.js

Leave a comment