React’s Higher Order Components I use the most

Mindaugas Nakrosis
2 min readApr 3, 2021

--

I have already written an article explaining what Higher Order Components (HOCs) are and about the advantages they offer. If you’re new to this concept, feel free to read about it: What is a Higher Order Component?

There are some HOCs that I use more often than others. I will write about the ones I use and like the most.

1. Hidable — conditional rendering of a component

const HidableComponent = ({ isVisible, children }) =>
isVisible ? <>{children}</> : null;
const hidable = (Component) => {
const WithHidable = ({ isVisible, …rest }) => (
<HidableComponent isVisible={Component && isVisible}>
<Component {…rest} />
</HidableComponent>
);
return WithHidable;
};

What this HOC does is it does not render your component if isVisible prop is passed as false. This can be used with combination of various state management tools.

2. Switcher — decides which component to render

const switcher = (selector) =>
React.forwardRef((props, ref) => {
const Component = selector(props);
return <Component ref={ref} {…props} />;
});

Switcher has a selector which decides which component to render. It can be used in a lot of ways, one of them is like this with redux:

const mapStateToProps = (state: State) => ({
isMobile: isMobileView(state),
});
export default connect(mapStateToProps)(
switcher(({ isMobile }) => (isMobile ? MobileView : DesktopView))
);

3. withInitialize — helps with lifecycle props

class Initializer extends React.Component {
constructor() {
if (this.props.onConstruct) this.props.onConstruct();
}
componentDidMount() {
if (this.props.onDidMount) this.props.onDidMount();
}
componentWillUnmount() {
if (this.props.onWillUnmount) this.props.onWillUnmount();
}
render() {
return <>{this.props.children}</>;
}
}
const withInitialize = (Component) => {
const component = ({ onDidMount, onConstruct, onWillUnmount, ...rest }) => (
<Initializer
onDidMount={onDidMount}
onConstruct={onConstruct}
onWillUnmount={onWillUnmount}
>
<Component {...rest} />
</Initializer>
);
return component;
};

Initializer class can be a functional component replacing lifecycle methods to hooks like useEffect. This HOC helps if you need some data fetching or other events to be fired on component initial load, mount or unmount.

4. withPreventedOnClick — prevents the onClick event on a component

const withPreventedOnClick = (Component) => ({ onClick, ...rest }) => {
const handleClick = (e, ...args) => {
e.preventDefault();
onClick(...args);
};
return <Component {...rest} onClick={handleClick} />;
};

These are the ones I use the most and find are very useful. Of course you can have hundreds of HOCs like these. Let me know what you think.

--

--

No responses yet