fosteman

Timothy Fosteman

Posted on June 20, 2019

HOC React

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]
Enter fullscreen mode Exit fullscreen mode

Array​.prototype​.for​Each()

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

Typical Math Abstraction

const multiply = (x) => (y) => x * y
multiply(1)(2) 
// -> 2
Enter fullscreen mode Exit fullscreen mode

Wild Caught oneliner

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

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)))
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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!

💖 💪 🙅 🚩
fosteman
Timothy Fosteman

Posted on June 20, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

HOC React
react HOC React

June 20, 2019