More

    React Loadable: Here’s Everything You Need to Know

    Introduction about React Loadable:

     In an attempt to have web applications serve various needs for various users, it is likely that more code is required that it would be for just one type of user. React Loadable allows the app to adapt and handle different scenarios and use cases, which lead to new features and functionalities. When this happens, it is understandable to expect the performance of an app to dwindle as the codebase grows. 

     Code Splitting- 

    Code splitting is a technique in which an application only loads the code that It requires at one particular time. For instance, when a user navigates to a homepage, there is probably no need to load the code that powers a backend dashboard. With code splitting, we can ensure that the code for the homepage is the only code that loads and provides optimal loading. 

     Code splitting can be conducted in a react application using React Loadable. It provides us with a Higher Order Component, that can be set up to dynamically import specific components at specific times. 

     

    Component Splitting- 

    There arise situations where we might want to unconditionally render a component on the basis of a user event, say when a user logs in to an account. A common way of handling this is to make use of state- the component gets rendered depending on the logged in state of the app. 

    We call this component splitting. 

    Below is an example of how this will look in code. 

     

    const Hello = () => {

        return (

            <React.Fragment>

                <h2>Hello</h2>

            </React.Fragment>

        )

    }

     

    class App extends React.Component {

      state = {

        openHello: false

      }

     

      handleHello = () => {

        this.setState({ openHello: !this.state.openHello })

      }

      render() {

        return (

          <div className=“App”>

            <button onClick={this.handleHello}>

              Toggle Component

            </button>

     

            {

              this.state.openHello ?

                <Hello />

              : null

            }

          </div>

        );

      }

    }

     

    ReactDOM.render(<App />, document.getElementById(“root”))

     

    Considering this is a basic example, say we want to conditionally render a component that contains an <h2> heading with “Hello”. Like this: 

     

    const Hello = () => {

                return (

                            <React.Fragment>

                                        <h2>Hello</h2>

                            </React.Fragment>

                )

    }

     

    We can customize an openHello state in the App component with an initial value of false. Then we can have a button used to toggle the state, either display the component or hide it. We’ll throw that into a handleHello method, which looks like this: 

     

    class App extends React. Component {

                state = {

                            openHello: false

                }

     

                handleHello = () => {

                            this.setState({ openHello: !this.state.openHello })

                }

                render() {

                            return (

                                        <div className=“App”>

                                                    <button onClick={this.handleHello}>

                                                                Toggle Component

                                                    </button>

     

                                                    {

                                                                this.state.openHello ?

                                                                            <Hello />

                                                                : null

                                                    }

                                        </div>

                            );

                }

    }

     

    Let us take a quick peek in the DevTools and take note of the Network Tab: 

     Next, let us use a refractor to make use of Loadable Hello. Instead of importing the component straight up, we will conduct the import using Loadable. We’ll start by installing the react-loadable package: 

    ## yarn, npm or however you roll

    yarn add react-loadable

     

    Now that this has been added to our project, we need to import it into the app: 

     import Loadable from ‘react-loadable’;

     

    We will now use Loadable to create a “loading” component which will look like this: 

    const LoadableHello = Loadable({

                loader: () => import(‘./Hello’),

                loading() {

                            return <div>Loading…</div>

                }

    })

     

    We pass a function as a value to loader which returns the Hello component we created. In this example, we will return a div element. 

     

    {

                this.state.openHello ?

                            <LoadableHello />

                : null

    }

     

    Now, our Hello component loads into the DOM only when the state is toggled by the button. 

     

    And this is what we call the component splitting ability. 

     

    Route-based splitting

     We have now seen how Loadables can be used to load components through the medium of other components. Another way to perform this is route-based splitting. 

    In this method, the components are loaded on the current route. 

     For example, if a user is on the homepage of an app and clicks on the Hello view with a route of /hello, the components that belong on that specific route would be the only ones that load. It’s a fairly common way of handling splitting in many apps and generally works well, especially in less complex applications.

     

    Here is a basic example of defined. Routes in an app. In the below case, we have two routes. 

    1)    Home (/) and 

    2)    Hello (/hello)

     

    class App extends Component {

                render() {

                            return (

                                        <div className=“App”>

                                                    <BrowserRouter>

                                                                <div>

                                                                            <Link to=“/”>Home</Link>

                                                                            <Link to=“/hello”>Hello</Link>

                                                                            <Switch>

                                                                                        <Route exact path=“/” component={Home} />

                                                                                        <Route path=“/hello” component={Hello} />

                                                                            </Switch>

                                                                </div>

                                                    </BrowserRouter>

                                        </div>

                            );

                }

    }

     

    As it so happens, all the components will render when a user switches paths, even though we only want to render the Hello. Component-based on that path. Sure, it’s not a huge deal if we are talking in terms of a few components but a larger size may cause added problems. 

     

    Using Loadable, we can import only the component we want by creating a loadable component for each object: 

     

    const LoadableHello = Loadable({

                loader: () => import(‘./Hello’),

                loading() {

                            return <div>Loading…</div>

                }

    })

    const LoadableHome = Loadable({

                loader: () => import(‘./Home’),

                loading() {

                            return <div>Loading…</div>

                }

    })

    class App extends Component {

                render() {

                            return (

                                        <div className=“App”>

                                                    <BrowserRouter>

                                                                <div>

                                                                            <Link to=“/”>Home</Link>

                                                                            <Link to=“/hello”>Hello</Link>

                                                                            <Switch>

                                                                                        <Route exact path=“/” component={LoadableHome} />

                                                                                        <Route path=“/hello” component={LoadableHello} />

                                                                            </Switch>

                                                                </div>

                                                    </BrowserRouter>

                                        </div>

                            );

                }

    }

     

    What about any errors and delays that are caused?

    If any imported components load fast, a need to flash a “loading” component does not arise. Thankfully, loadable has the ability to delay the loading component from showing. This is helpful to prevent it from displaying too early where it feels silly and instead show it after a notable period of time has passed where we would expect to have seen it loaded. 

     In order to do this, our sample loadable component should look like this:  

    const LoadableHello = Loadable({

                loader: () => import(‘./Hello’),

                loading: Loader,

                delay: 300

    })

     

     Now, let us add a condition to the Loader component that tells it to display the loader only after the 300ms delay we set has passed. 

     

    const Loader = (props) => {

                if (props.pastDelay) {

                            return <h2>Loading…</h2>

                } else {

                            return null

                }

    }

     

    If we do this, the loader component will only show if the Hello component. It Will not show after 300ms. 

     React loader. Also gives us an error prop that we can use in order to return. Errors that are encountered. 

     

    const Loader = (props) => {

                if (props.error) {

                            return <div>Oh no, something went wrong!</div>;

                } else if (props.delay) {

                            return <h2>Loading…</h2>

                } else {

                            return null;

                }

    }

     

     It is important for us to know that we are actually combining the delay and error handling. Together. 

     

    Recent Articles

    React Ecommerce Templates

      React is the most popular library for the development of e-commerce applications. React eCommerce templates for building eCommerce apps are a combination of several...

    What is React Yarn? How to Install It?

    Introduction to React Yarn The technical community shares hundreds and thousands of pieces of code every day in the community of JavaScript. As a result,...

    React Editor: Features, Installation and Limitations

    Why do we need the react editor?  There is a large range of code-based editors like CodeMirror, Monaco, Ace, etc., that provide us with the...

    React Babel: Everything You Need to Know About It

    Introduction About React Babel: React Babel is a very well known and well-implemented open-source transcompiler of JavaScript. We use it mainly to convert the ECMA...

    React Websocket: Usage, Installation and much more

    Introduction About React Websocket:  If you want to create a long-running connection between a client and a server then use React Websocket. Let's take an...

    Related Stories

    Leave A Reply

    Please enter your comment!
    Please enter your name here