DEV Community

loading...

HOC React

fosteman profile image Timothy Fosteman Updated on ・2 min read

This is my first post on dev.to
Warm hello to everyone!

There's an old saying "Don't Repeat Yourself". If applied to React codebase - a worthwhile challenge involving High Order Functions (HOF).

Before delving into code,
couple of HOF examples:

Array.map

[1, 2].map(el => el = el + 1);
// → [2, 3]

Array​.prototype​.for​Each()

["A", "B"].forEach(l => console.log(l));
// → A
// → B

Typical Math Abstraction

const multiply = (x) => (y) => x * y
multiply(1)(2) 
// -> 2

Wild Caught oneliner

Function Composition
const composition = (...callbacks) => callbacks.reduce((a,b) => (...args) => a(b(...args)));

Decodes as:

const compose = (...callbacks) => callbacks.reduce((a, b) => (...args) => a(b(...args)));
    const addTwo = x => x + 2;
    const double = x => x * 2;
    const square = x => x * x;
    const fn = compose(addTwo, double, square);
    console.log(fn(1)); // -> 4 addTwo(double(square(1)))

HOC in React ...

HOC is a pattern that emerges from React’s compositional nature.

Note, that HOC is an advanced pattern used in React, but not the part of API. You can use them to abstract functionality away but reuse it as opt-in functionality for multiple components. A higher order component takes a component and optional configuration as input and returns an enhanced version of the component. It builds up on the principle of higher order functions in JavaScript: A function that returns a function.

HOC are important later on, because you will be confronted with them when using Redux. (connect HOC in react-redux).
These are the means to abstract given React Components implementing logic and returning a freshly augmented Component

Prototype is this:

const AugmentedComponent = HOC(OriginalComponent);

To demonstrate, the following function returns component <ReversedNameComponent> with reversed innerText of originally passed <OriginalNameComponent>:

const reverse = ChildComponent =>
  ({ children, ...props }) =>
    <ChildComponent {...props}>
      {children.split("").reverse().join("")}
    </ChildComponent>

const OriginalNameComponent = props => <span>{props.children}</span>

const ReversedNameComponent = reverse(OriginalNameComponent)

Receives ChildComponent, splits string on Array of characters, reverses the order, joins into new string, returns result back into Component's innerText

Thanks for reading!

Discussion

pic
Editor guide