Higher Order Components (HOC) in React

A Higher Order Component is a function that takes a component as an input argument and returns a new component.

When we have Class Based and Functional Component, then what is the need of Higher Order Components?

Let's read in detail why we need Higher Order Components in React.js

What are the benefits of using Higher Order Components (HOC) in React.js?

It's mainly for reusability. Rather than writing same logic/code again and again you can encapsulate the feature in a higher order component and you can use it.

Let me explain you with an example.

Suppose you have some sections in app which can be accessed by authenticated users only. How will handle this scenario?

One elementary solution is by adding a check in componentWillMount() lifecycle method. but this is not an optimized solution. Will you copy paste the logic everywhere? -
Solution is - Higher Order Components (HOC)

Example

Suppose we have dashboard which only authenticated users can access, and perform some task like edit, view, and delete task records.

<Route path="/" component={App}>
    <Route path="/dashboard" component={Documents}/>
    <Route path="document/:id/view" component={ViewDocument} />
    <Route path="documents/:id/delete" component={DelDocument} />
    <Route path="documents/:id/edit" component={EditDocument}/>
</Route>
class Doucments extends React.Component {
    componentwillMount() {
        if(!this.props.isAuth){
            this.context.router.push("/")
        }
    }
    componentWillUpdate(nextProps) {
        if(!nextProps.isAuth) {
            this.context.router.push("/")            
        }
    }
    render() {
        return 
Documents Paegs!!!
} } function mapstateToProps(state) { isAuth: state.auth } export default connect(mapStateToProps)(Documents)