React — higher order components(HOCs) — some use cases

Manish
All is Web
Published in
2 min readOct 3, 2018
Photo by Patrick Schneider

React provides us with a very powerful technique to reuse an existing component’s logic, and yet empower this component with additional features. Yes, we are talking about higher order components(HOCs from here on). For many react ninjas out there, this might seem a trivial pattern but from my repeated discussions with many others, i felt the need to pen(well type) a few use cases down. So, here we go.

showing a loader, while a component waits for data

a very frequently needed feature in our app is to show a loader while a component is waiting for data to be passed into it’s props. of course an in-component solution to have a loader can work, it won’t be the most elegant solution. the idea is to create a common HOC, that can track that prop and while it’s empty, can show a loading state.

Conditionally rendering components

there could be a case with many components, when those components are to be shown if a certain criteria is met with the data that is provided in their props. since HOCs have access to the wrapped component props, we can have a reusable HOC that conditionally renders the component based on the data provided.

managing common user-interaction states

let’s accept this, users feel pampered when our application controls respond just to their cursor movements. yes i am talking about hover effect. ui states like hover, focus etc can be displayed beautifully, without repeated handlers with each component, by abstracting to an HOC which can have an event hook to augment the wrapped component with a state specific flag.

providing components with specific styles

continuing from last point, based on the flag that we get form the HOC, we can have flag specific styles not only for user interaction states, but also data specific ones. moreover, some more trivial styles, if the need arises at multiple places, like backgroundColor, fontSize etc can be easily provided via an HOC by wrapping the component with one, that just augments props with the specific className(s).

and more generally, provide a component with just any prop that you want

keeping the above in mind, we can keep an eye on what reusable prop is needed across different components and consider having a wrapper HOC to provide those with one.

random fact: The name for the shape of Pringles is called a ‘Hyperbolic Paraboloid’.

--

--