React Higher Order Component (HOC)

Photo by Andrew Neel on Unsplash

React Higher Order Component (HOC)

Hello guys, Today I'm going to explain about Higher Order Components in React,

What is HOC

HOC is a function that gets a Component as an argument and returns another Component instead of JSX, we are using these components to share complex logic and behaviours with more UI components and also to add extra functionalities to components.

// Normal Component
Component => <div>JSX</div>

// HOC
HOC => Component => <div>JSX</div>

Confused😳 Let's see more examples,

// User Component
const User = ({ name }) => <div>Name - {name}</div>

// Let's create a HOC to print props
const withPrintProps = (Component) => {
    return (props) => {

        return <Component {...props} />

// Let's create a User component with print props functionality
const UserWithPrint = withPrintProps(User)

// usage
function App = () => {
    return <UserWithPrint name="Dileepa Chandima" />

So here what we added is to print the props to the console, But I think now you have a good understanding of how HOC works,

This is a small list of HOC usages,

  • Add logs to the components (eg: Sentry logs)

  • Add event tracking for marketing purposes

  • Redux connect is a usage of HOC

  • Add Data fetching logic according to the props