React ~ Component Patterns ~ HOC (High Order Component) - rohit120582sharma/Documentation GitHub Wiki
When we want an abstraction that allows us to define a logic in a single place and share it across many components, this is where HOC comes into the picture. A HOC is just a pattern of components architecture in React and used to share common functionality between components without repeating code.
It is a function which takes a component as an argument and returns a new component. The component, it returns can render the original component that was passed in. It transforms a component into another component and adds additional data or functionality.
A HOC is a pure function with no side-effects. It doesn’t modify the input component. Rather, a HOC composes the original component by wrapping it in a container component. You can think of HOCs as parameterized container component definitions.
But, when using a HOC, there’s an inversion of control happening.
Note: Do not use HOC’s in the render method of a component. Access the HOC outside the component definition.
function withHover(Component, propName = 'hovering') {
return class WithHover extends React.Component {
state = { hovering: false }
mouseOver = () => this.setState({ hovering: true })
mouseOut = () => this.setState({ hovering: false })
render() {
const props = {
[propName]: this.state.hovering,
...this.props,
};
return (
<div onMouseOver={this.mouseOver} onMouseOut={this.mouseOut}>
<Component {...props} />
</div>
);
}
}
}
function Info({showTooltip, height}) {
return (
<div>
{showTooltip === true
? <Tooltip id='info' />
: null}
<svg
className="Icon-svg Icon--hoverable-svg"
height={height}
viewBox="0 0 16 16" width="16">
<path d="M9 8a1 1 0 0 0-1-1H5.5a1 1 0 1 0 0 2H7v4a1 1 0 0 0 2 0zM4 0h8a4 4 0 0 1 4 4v8a4 4 0 0 1-4 4H4a4 4 0 0 1-4-4V4a4 4 0 0 1 4-4zm4 5.5a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3z" />
</svg>
</div>
);
}
const InfoWithHover = withHover(Info, 'showTooltip');
Two HOC’s implementations that you may be familiar with in the React ecosystem are connect from Redux and withRouter from React Router.
The connect is a function that returns another function. In other words, connect is a higher-order function that returns a higher-order component! The returned function is a HOC, which returns a component that is connected to the Redux store
const enhance = connect(commentListSelector, commentListActions);
const ConnectedComment = enhance(CommentList);