HOF and HOC (in React)

📄 Table of Contents

Higher-Order Functions (in JS)

1. Takes one or many functions as arguments

function addTwice(f, v) {
return f(f(v));
}
function add(v) {
return v + 3;
}
const result = addTwice(add, 1);
console.log("Result is ", result);
<code class="">Result is 7

2. Returns a function

Tricky?

Examples

Creating Our own Higher-Order Function

let names = ['John', 'Mac', 'Peter'];
let lengths = names.map(name => name.length);

console.log(lengths);

Higher-Order Component (in React)

The most simple HOC

Use HOC to enhance components

Example no: 2

Use Cases

Observations

A Higher-Order Component Example

const hoc = (WrappedComponent) => (props) => {
return (
<div>
<WrappedComponent {...props}>
{props.children.toUpperCase()}
</WrappedComponent>
</div>
)
}
const Username = (props) => (
<div>{props.children}</div>
)
const UpperCaseUsername = hoc(Username)
const App = () => (
<div>
<UpperCaseUsername>Kingsley</UpperCaseUsername>
</div>
);
HOC template
My Username component

References:

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.