• Home
  • React – what is HOC?

React – what is HOC?

So today I will try to explain what is HOC ( Higher Order Component ) and why we use this type of components in React Apps. Explanation of HOC from React docs is:  “A higher-order component is a function that takes a component and returns a new component”. Manny beginners in React are not aware that with HOC can create better apps without repeating code. Let’s see that in example. Let say that we need authorization in our app and we need to be sure that component is not shown if user is not logged in without HOC we can write something like this:

class FirstComponent extends React.Component {
  render() {
    if (this.props.isLoggedIn) {
      return <p>hi</p>
    }
    return <p>You're not logged in ☹️</p>
  }
}
// repeated code!
class SecondComponent extends React.Component {
  render() {
    if (this.props.isLoggedIn) {
      return <p>hi</p>
    }
    return <p>You're not logged in ☹️</p>
  }
}
// notice how we need different logic for functional components
const FunctionalComponent = ({ isLoggedIn }) => ( isLoggedIn ? <p>Hi There</p> : <p>You're not logged in ☹️</p> )

And now let’s this with HOC

function AuthWrapper(WrappedComponent) {
  return class extends React.Component {
    render() {
      if (this.props.isLoggedIn) {
        return <WrappedComponent {...this.props} />
      }
      return <p>You're not logged in ☹️</p>
    }
  }
}

class FirstComponent extends React.Component {
  render() {
    return <p>hi</p>
  }
}
class SecondComponent extends React.Component {
  render() {
    return <p>hello</p>
  }
}
const FunctionalComponent = () => (<p>Hi There</p>)

const WrappedOne = AuthWrapper(FirstComponent)
const WrappedTwo = AuthWrapper(SecondComponent)
const WrappedThree = AuthWrapper(FunctionalComponent)

The AuthWrapper component lifts all authentication logic into a unifying component. All it does is take a prop called isLoggedIn and returns the WrappedComponent or a paragraph tag based on whether or not that prop is true or false.

As you can see, HOCs are extremely useful because they let us reuse code and remove bloat. We’ll get more practice with these soon!

Thanks for reading…

Tags: ,

Copyright by Kristijan Klepač 2018