Skip to content

Instantly share code, notes, and snippets.

@mikaelbr mikaelbr/hocs.md
Last active Jan 31, 2018

Embed
What would you like to do?

Higher Order Components vs Higher Order Functions operating on Components (HoFooC™)

A higher order function would be a function taking a function as input, or returning a function. Such as:

function logger (fn) {
  return function (...args) {
    console.log('Invoking with', ...args);
    return fn(...args);
  };
}

So this is a higher order function as it takes and in this case it also returns a function. But here the function part of higher order functions refer to the logger function (the reciever, not the entity being operated on). So you could say that this:

function loggerComponentFunction (MyComponent) {
  return function DecoratedComponent (props) {
    console.log('Rendering with', ...props);
    return <MyComponent {...props} />;
  };
}

isn't a higher order component, if you define a component as a function returning a valid render item in React (a component could be a general term in computing, but let's use that definition). And rather that this is a proper higher order component:

function LoggerComponent ({ MyComponent }) {
  console.log('Rendering MyComponent');
  return <MyComponent foo="Hello" />;
}

As this is a component taking a component as argument.

But I think that would be kind of splitting hairs and the real value of this pattern is altering behaviour of a component and returning a component with more specialized behaviour or the like. It really comes down to semantics. But either way both above examples are definitly higher order. But wether we call them Higher Order Components or Higher Order Functions operating on Components (HoFooC™), is kind of beside the point I think.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.