Higher Order Components (“HOCs”) are the latest hotness to come out of the JavaScript idea world and land in our apps. React apps, anyway.
I really want to write: Higher Order Components are just wrappers, but that would be simplifying the concept too much. Wouldn’t it? Maybe.
Anyway, they’re wrappers. Keep your actual Component simple as pie – it takes ingredients as props and turns them into rendered flaky crust – and have the wrapper handle getting the data from wherever, massaging it, and jamming it in.
This makes the underlying Component simpler to understand, debug, and ultimately reuse elsewhere if needed. Also testing! It’s way easier to test when the data piece is separate.
After thinking about it for a while you may realize that this concept is not new. Keep a pie-making machine abstract and separate from the ingredient machine? Where have we seen this before? Functions! (Ok, other places too.) And lo, this seems to be where React is heading (has already arrived?): Components as functions.
A Component, ideally, should take its props, nothing else (except maybe more Components) and turn those props into output. The output should be the same no matter what as long as the props are the same. It can use libraries to process the data it already has, but not get new data. I mean, that was an idea that React was built upon. But hey, I’d say that’s also the definition of a good function.
So if we think about our Components as functions, then we can apply function strategies to them. Mine basically boil down to: can this be done in fewer lines by extracting logic into a sub-function? Repeat as necessary until my functions are thin little beautiful pancakes. Maybe you have different strategies. Try them on Components!
Usually I see HOCs being talked about in reference to Redux and the global state tree, but my favorite thing is: who cares where the data comes from? Nest those Components and let them remain simple. The HOC could pull data from many sources, even just from a JSON file.
My new rule of thumb is: whenever my Component starts getting too many props (that are not directly related to its concept), when I am pulling data into my Component from a library, or when I find myself caching data in a Component’s state, there’s a strong chance I could use an HOC to smooth things out.
Give it a try! You may be surprised at how fun it can be.