The beauty of higher order functions

Daniel Lichtenstein
2 min readOct 9, 2015

--

Today was a magnificent day, although that is probably taking it a step too far. In any case, this was the day that I had another one of those pleasant ‘aha’ experiences related to functional programming and React. You see, they recently released React v0.14, and with it comes stateless components.

const Component = props => <div>{props.hello}</div>

That is equivalent to writing this:

const Component = React.createClass({
render() {
return <div>{this.props.hello}</div>;
}
});

And the beauty of it all is that it goes one step further in showing that React components are, more than anything else, functions. A transformation of input to output, where the output is “markup”.

And this is exciting because functions are, frankly, quite magical.

And the point I am trying to make? Well, that would be higher order functions, and how this concept relates to React in a truly beautiful way.

A simple higher order function would be something like this:

const Helloer = Component => props => <Component hello="world" />;

As this would be a function that takes a function as its first argument lets see how we can use it together with the first function.

const HelloWorld = Helloer(Component);<HelloWorld /> === <div>world</div>;

Not very exciting to be sure, but when you realise that you can use the ‘Helloer’ function to inject the ‘hello’ property into all sorts of different component, that opens up many doors for you. This concept of higher order functions is what allows you to move away from mixins for instance.

Beyond making a couple of functional realisations today, I was struggling with another issue. Should I use CSS :pseudo classes or not? That ‘:hover’ for instance is so nice to use, right? What I ended up doing is building that behaviour using a higher order function, WatchHover, it looks something like this. It doesn’t use the fancy new stateless function syntax, but that is for good reason, it isn’t stateless. It needs to keep track of whether the mouse enters or exits the component.

What’s nice is that I now can use the hover behaviour in other components.

const isHovering = props => <div>{props.hover ? 'yes' : 'no'}</div>;const activated = WatchHover()(isHovering);

(The empty () in the WatchHover call is there in case you want to map the hover state to your props differently, in case you are wondering.)

If that isn’t beautiful, I’m not sure what is!

--

--