Table of contents
Open Table of contents
Higher Order Function
To understand higher order component in react js, we first need to understand what is higher order functions are
Let’s try to understand Higher order functions in javascript.
Higher order functions are functions which take one or more functions as an arguments and return new function.
map, filter, reduce are some of the common in built higher order functions in javascript.
How to create your own Higher order function
Let’s take an example.
Let’s say we want to get evens numbers from array.
function getEvenNumbersFromArr(arr) {
let res = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 === 0) {
res.push(arr[i]);
}
}
return res;
}
getEvenNumbersFromArr([1, 2, 3, 4, 5, 6]);
Now we want to get odd numbers from array
function getOddNumbersFromArr(arr) {
let res = [];
for (let i = 0; i < arr.length; i++) {
if (arr[i] % 2 !== 0) {
res.push(arr[i]);
}
}
return res;
}
getOddNumbersFromArr([1, 2, 3, 4, 5, 6]);
As you can see we are repeating for loop here. It is a violation of Don’t repeat yourself principle. With HOCs you can avoid code duplication and write more modular applications.
Let’s try to improve the above code.
const isEven = num => {
return num % 2 === 0;
};
const isOdd = num => {
return num % 2 !== 0;
};
// Higher Order function
function getOddEvenNumber(arr, callback) {
let res = [];
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i])) {
res.push(arr[i]);
}
}
return res;
}
getOddEvenNumber([1, 2, 3, 4], isEven);
Now you have understood what are HOCs, Let’s try to understand what are Higher Order Components.
Higher Order Component
A HOC is a simple JavaScript function which accepts a component or another js function and returns a completely new enhanced component based of the first one.
The HOCs are nothing more than a way of reusing code to create cleaner and simpler React components.
Let’s try to learn HOC using example. Let’s say you have want to display list of products using cards components and using table components. First thing comes to our mind is to create two components and inside components we call the api and return some data and display some data. But here we are repeating some code. To avoid this we can use HOC.
To build HOC functionality we should remember three things.
- create HOC function
- create Table component
- create Cards component
HOC function has three parts.
- create a component which takes component as an argument
- create a component inside HOC component, do some repeating code and return component which comes from an argument
- return inner component
// WithFetch.js
import { useEffect, useState } from "react";
function WithFetch(WrappedComponent) {
const WithFetch = () => {
const [products, setProducts] = useState([]);
useEffect(() => {
// fetching api
try {
fetch("https://reqres.in/api/users?page=2")
.then(res => {
return res.json();
})
.then(data => {
setProducts(data.data);
});
} catch (error) {
console.log(error);
}
}, []);
return <>{products.length > 0 ? <WrappedComponent /> : null}</>;
};
return WithFetch;
}
export default WithFetch;
How to use HOC component ? import HOC function and wrap the component with HOC
// UserCards
import WithFetch from "./withFetch";
function UserCards({ users }) {
return (
<>
<div>User lists with HOC functions</div>
{users.map(user => {
return <UserCard user={user} />;
})}
</>
);
}
export default WithFetch(UserCards);
// UsersTable
import WithFetch from "./withFetch";
function UserTables({ users }) {
return (
<>
<div>User lists with HOC functions</div>
{users.map(user => {
return <UserTable user={user} />;
})}
</>
);
}
export default WithFetch(UserCards);
Common Use Cases:
- Authentication: Create an HOC that checks user authentication status and redirects unauthorized users if necessary.
- Data Fetching: Use an HOC to fetch data from external APIs and make it available as props to the wrapped component.
- Styling: Implement component-specific styling or theming through an HOC, avoiding inline styles or class proliferation.
- Error Handling: Create an HOC that wraps components and handles errors globally, providing a consistent user experience.
- Logging: Track component lifecycle events or prop changes for debugging purposes using an HOC.
- Performance Optimization: Employ memoization or techniques like React.memo with HOCs to optimize component performance.