React tips — Higher Order Components

Leonardo Bruno Lima
2 min readApr 9, 2018
Photo by Charles Deluvio 🇵🇭🇨🇦 on Unsplash

In short, a higher-order component is a function that takes a component and returns a new component, nothing else more.

Sometimes you may want extend a component to give more functionality but don’t want add directly on it for many reasons. Let’s see an example:

//HoC for check authenticationimport React, { Component } from 'react';
import { connect } from 'react-redux';
export default (ComposedComponent) => {
class RequireAuth extends Component {
componentWillMount() {
if (!this.props.authenticated)
this.props.history.replace("/");
}
componentWillUpdate() {
if (!this.props.authenticated)
this.props.history.replace("/");
}
render() {
return (
<ComposedComponent { ...this.props } />
)
}
}
function mapStateToProps({ auth: { authenticated }}) {
return {
authenticated
}
}
return connect(mapStateToProps)(RequireAuth);
}

In this example, we’ve created a function that receives a component as argument and check (via Redux) if the user is authenticated, if not redirect to “/”.

In this example, connect is also a Hight Order Component, that allow our component to access the store and action creators with Redux.

As you can see, we didn’t add any new behavior to original component, but it will only be rendered if the user is authenticated. This is one way to protect components that can only be access after user log in. Let’s see how we could use this HoC:

In this example above, the Stores, StoreProducts, Cart and OrderList components can only be accessed if user is authenticated.

Thanks,

--

--