Better ReactJS project structure by Higher Order Components

Have you ever experienced that you need to use a function again and again in the same app? Does it make your codes messy and complicated?

The good news is that the higher-order components (HOC) came to serve us to clean our code. HOC is not a feature or a part of the React API but rather an advanced technique making the component logic reusable in React.js. This technique is evolved in the light of this React structure that props can pass from one component to the other. It decomposes the logic into smaller reusable functions leading to complexity reduction and much easier debugging and maintenance. Just pass props into HOC and get your desired component in return.
HOC is applied to simplify many tasks in React.js; however, in this article, we utilize HOC to create a “loading…” text to call it in different other components. It is used in the time lag between rendering and loading data from API, and improves the user experience, significantly. Also, you may be interested in watching my Video about creating this HOC ‘loading…’ more in detail.

Please subscribe using this link to get more related videos: https://www.youtube.com/channel/UCEoaRTl5alo9tw3A-eDJV9Q?sub_confirmation=1

Here we have a simple project of a drop-down component that shows a list of users’ names in the avatar when being clicked. As you know, there is a lag time between choosing a user and displaying his/ her profile. We want to create a HOC of “loading…” to be shown when the data is downloading from API. For This purpose, we have a “profile container” and a “profile component”. The former does the logic & business-related jobs, and the latter does UI- related jobs like getting data and displaying it. In the following code, you can see how the HOC is written by a simple conditional phrase. If the isLoading state is true, show ‘loading…’ otherwise show profile component. We call this component withLoading.

import React, { Component } from 'react'
function withLoading (WrappedComponent) {
    return class extends Component {
        render () {
            return this.props.isLoading ? 'Loading...' : <WrappedComponent {...this.props} />
        }
    }
}

export default withLoading

Now, this HOC function is ready; we can apply it anywhere in our app without repeating the whole function again and again. Just add a conditional phrase of isLoading to the “profile container” and connect the function of redux in “profile component” using the following code.

export default withLoading(Profile)

Then pass the isLoading props to the withLoading HOC and enjoy it.

#reactjs #react #hoc #reactnative #web

Better ReactJS project structure by Higher Order Components
37.20 GEEK