Simply put, Higher Order Component(HOC) is a function that takes in a component and returns a new component.
When do we need a Higher Order Component?
While developing React applications, we might develop components that are quite similar to each other with minute differences.
In most cases, developing similar components might not be an issue but, while developing larger applications we need to keep our code
DRY, therefore, we want an
abstraction that allows us to define this logic in a single place and share it across components.
HOC allows us to create that abstraction.
Example of a HOC:
Consider the following components having similar functionality
The following component displays the list of articles:
class ArticlesList extends React.Component{
constructor(props){
super(props);
this.handleChange = this.handleChange.bind(this);
this.state = {
articles : API.getArticles();
}
}
componentDidMount() {
//Listen to changes made in the API
API.addChangeListener(this.handleChange);
}
componentWillUnmount() {
// Clean up listener
API.removeChangeListener(this.handleChange);
}
handleChange() {
// Update the articles variable whenever the API changes
this.setState({
articles: DataSource.getArticles()
});
}
render(){
return(
<div>
{this.state.articles.map((article)=>(
<ArticleData article={article} key={article.id}/>
))}
</div>
)
}
}
The following component displays the list of users:<div style="box-sizing: border-box; margin: 0px; padding: 0.2em 0.6em; border-width: 0.1em 0.1em 0.1em 0.8em; border-style: solid; border-color: gray; border-image: initi