Higher order functions or components is one of those ideas that have had
a huge influence on how I think about solving problems. I have written
about it in the past, but the basic idea behind them is that a Higher
Order X is a X that will return a X or takes one or more X as a
For example: a function that takes a function as a argument or returns a
new function; or a component.
Note: it returns a actual function or takes a actual function as a
argument, and not the result from a function.
I assume the passing function / components as arguments is the easiest
to understand concept out of the two. Like I mentioned above, it is a
way to re-use the same code without adding a lot of complexity to the
code. Let’s for example say that you have a lot of components that show
a list of “stuff”. And it also needs to have a way to fetch the data.
The way you could solve this is to add a lot of if / else to solve it;
or you could use higher order to solve it. The latter is easier to
maintain, extend and use.
I would solve this by passing a “fetch” or “update” function to the list
component, plus a item component; both as props. This means that the
component would run this.props.fetch to load stuff, and use
this.props.item to render the items in the list. And it would be easy to
extend to manage editing and deleting, because you only need the logic
in the list component and all you need to do in each use of it is update
delete and save functionality.
The other type is a little bit harder to grasp. But as I said, the basic
idea is that a function returns a function and a component returns a
component. Let’s say you need to implement a check to validate if the
user is authenticated. You could add some code to check it, all over the
place, or you could wrap it with a higher order component. Where the
logic for testing and telling you that you don’t have access is in one
place and you just call it with your component as a argument to get them
wrapped component back.
This is by the way how the redux connect() method works; the method you
use to connect state from redux to component props.
Look at the example above, I haven’t actually tested it; but it shows
the basic idea. You have a generic “list” and a generic “item”.
You pass what “item” to use, and what update and delete methods to use
to the parent; and you could use some like the example above for listing
out more or less anything. The only thing that would change would have
been the update methods, and you could even add extra “item” components