Higher Order Component for listing data using FlatList in React Native

Aravind Madhusudhanan Nair
2 min readFeb 5, 2022

Image Credit: interviewbit.com

If you’ve been using React or React Native for some time, you might have felt the need to have copies of the same logic in multiple components.

What are Higher Order Components?

According to ReactJS documentation,
A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React’s compositional nature.

So, just like a Higher-Order Function in functional programming in JS , which takes a function as an argument and/or returns a function, HOC is a pattern that stems from React’s nature that privileges composition over inheritance. So, simply speaking, — A higher-order component(or HOC) is a function that takes a component and returns a new component.

So, let’s get straight to the point and create an HOC for listing items using FlatList with an ActivityIndicator that can be reusable in multiple screens, without the need of rewriting the logic again and again.

Building the Wrapper or Higher Order Component

Below, you can see that we have created an HOC that accepts a component Comp, isLoading prop for showing the spinner and some extra props for the FlatList.

If isLoading is true, then we render the spinner or ActivityIndicator or else we render the component which is passed along with the props it has, and in here the FlatList will be rendered.

Now we can use this HOC in our list screens like below:

At first, we have imported the HOC in our listing screen and then we pass the component that we need to wrap to the HOC. In our case, we pass the FlatList component from the react-native.
Similarly, you can use any other component based on our use-case. Here, we can directly use ListWithLoader and supply all the FlatList props directly to it along with the isLoading prop. The same can be done on any other screens for the same use-case, making the code less repetitive and clean.

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Aravind Madhusudhanan Nair
Aravind Madhusudhanan Nair

Written by Aravind Madhusudhanan Nair

Writes about JS, React and React-Native development and other technology stuff.

Responses (1)

Write a response

Is this really HOC ???

I mean it just looks like a normal component..