Skip to content

Instantly share code, notes, and snippets.

@mikaelbr
Last active January 31, 2018 00:25
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikaelbr/c34b6b9bcd63906e1dc5a8d82a7f9324 to your computer and use it in GitHub Desktop.
Save mikaelbr/c34b6b9bcd63906e1dc5a8d82a7f9324 to your computer and use it in GitHub Desktop.

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