React Js Higher Order Component Example Tutorial

In this article, we will see how to create a new component by passing a component as an argument into another component. This guide will show you how to build higher-order components and use higher-order components from a common logic-sharing perspective.

The Hoc concept is good, but you need to keep in mind that you use HOC only when you have to share the common logic. The data behavior has to be identical when creating and using HOC in React.

If you have been working with React for a while, you must have come across the term HOC (Higher Order Component). A higher-order component is a handy technique that allows us to reuse the component logic repeatedly.

Theoretically, a React component converts props into UI, but a higher-order component transforms a component into a new component. HOCs are not part of the core React API; instead, they are a pattern derived from React’s compositional nature.

A higher-order component is a simple function that accepts a component as an argument and returns a new transformed component. Ideally, the HOC component is used to share the common programming logic.

When we pass another component in the HOC component as an argument, the new component reads the common logic of HOC and converts itself into a newly transformed component.

How to Handle API Response using Higher Order Component in React Js

  • Step 1: Install New React Project
  • Step 2: Build New Components
  • Step 3: Set Up HOC in React
  • Step 4: Fetch Data using HOC
  • Step 5: Render Data through HOC
  • Step 6: Start React Project

Install New React Project

You can use the given command to install the new React app.

npx create-react-app react-blog

App is ready, enter into the React project.

cd react-blog

Build New Components

Components are reusable at the same time independent piece of code, they are created to serve the purpose of Js functions.

We will create components folder, inside this directory make the Posts.js file and add the given code.

import React from 'react'

function Posts() {
  return (
    <div>Posts</div>
  )
}

export default Posts

Make another file name it Users.js also add the given code into it.

import React from 'react'

function Users() {
  return (
    <div>Users</div>
  )
}

export default Users

Set Up HOC in React

In the src folder, you have to make the MainHoc.js file, add the following code within the file.

import React from 'react'

const MainHoc = (WrappedComponent, entity) => {
  return class extends React.Component {
    state = {
      list: [],
      query: '',
    }
    componentDidMount() {
      const getResponse = async () => {
        const resonse = await fetch(
          `https://jsonplaceholder.typicode.com/${entity}`,
        )
        const json = await resonse.json()
        this.setState({ ...this.state, list: json })
      }
      getResponse()
    }
    render() {
      let { query, list } = this.state
      let resItem = list.slice(0, 8).filter((res) => {
        if (entity === 'users') {
          const { name } = res
          return name.indexOf(query) >= 0
        }
        if (entity === 'posts') {
          const { title } = res
          return title.indexOf(query) >= 0
        }
      })
      return (
        <div>
          <h2>React Higher Order Component Example</h2>
          <div>
            <input
              type="text"
              value={query}
              onChange={(e) =>
                this.setState({ ...this.state, query: e.target.value })
              }
            />
          </div>
          <WrappedComponent data={resItem}></WrappedComponent>
        </div>
      )
    }
  }
}

export default MainHoc

Fetch Data using HOC

Import the MainHoc component; it will be used to accept the Users component as a parameter, and the ‘users’ property will be used as an entity.

Head over to Users.js file, place the suggested code in the file.

import React from 'react'
import MainHoc from '../MainHoc'

const Users = ({ data }) => {
  let users = data.map((item) => {
    return <div key={item.id}>{item.name}</div>
  })

  return <div>{users}</div>
}

const UsersList = MainHoc(Users, 'users')

export default UsersList

Render Data through HOC

You also need to add the MainHoc component in Posts component for making the HTTP request to fetch the data. Add the given code into the src/Posts.js file.

import React from 'react'
import MainHoc from '../MainHoc'

const Posts = ({ data }) => {
  let post = data.map((res, index) => {
    return <div key={index}>{res.title}</div>
  })

  return <div>{post}</div>
}

const PostList = MainHoc(Posts, 'posts')

export default PostList

We have build the two components using a simple higher order component, now you need to open and import the given code into the App.js file.

import React from 'react'
import PostList from './components/Posts'
import UsersList from './components/Users'

function App() {
  return (
    <div>
      <PostList />
      <UsersList />
    </div>
  )
}

export default App

Start React Project

We are now ready to run the react app, you need to start the development server using the given command.

npm start

Check the application on the browser with the given link.

http://localhost:3000

React Js Higher Order Component Example Tutorial

Summary

Why does the need arise to use higher-order components in React? As we have said before, we use HOC in React to reuse the logic in React apps.

Hoc is generally rendered UI in React; in this guide, we learned how to create a HOC component in React and dynamically make the Two diffrent HTTP requests through the Higher-order component mechanism.