Higher order Component (HOC) in React

In today post we are going to learn about HOC i.e Higher Order Component in React. A higher-order component in React is a pattern used to share common functionality between components without repeating code.

What is HOC ?

In React, we extend this concept to components, and so we have a Higher Order Component (HOC) when the component accepts a component as input and returns a component as its output.

In general, higher order components allow you to create code that’s composable and reusable, and also more encapsulated.

We always try to name our HOC component with With keyword. Like withRouter, withAuth etc. Which is just an convention.

Simple example of HOC

const withButton= Button => () => <Button />

In the above example a function named withButton is accepting a component i.e Button and returning it without modification.

When to use HOC

Higher order component is mainly used for reusable functionality. Some of the places where we can use HOC is given below

  • When we are doing same functionality at multiple locations.
  • Notification logic for your app.
  • Adding extra prop to your component i.e id, userName etc.
  • Checking for user login or not.

How to use HOC

Let’s create an example of HOC. Which basically gonna accept a Component and gonna add styling to it.

const withStyle = Element => props => <Element {...props} style={{color:"red"}} />

We write an HOC with name withStyle. Which gonna accept a Component as input and gonna return it with our custom styling.

const Button = () => {
  return <button>test</button>

const StyledButton = withStyle(Button)

We will simple render above component in our app now.

function App() {
  return (
    <div className="App">
      <StyledButton />

Rules to use HOC

There are few rules that we should follow while creating HOC.

  • A HOC should be a pure function with no side-effects. It should not make any modifications and just compose the original component by wrapping it in another component.
  • Do not use HOC’s in the render method of a component. Access the HOC outside the component definition.
  • Static methods must be copied over to still have access to them. A simple way to do this is the hoist-non-react-statics package.
  • Refs are not passed through.

I hope you have learned about Higher order Component (HOC) in React.


You can learn Best way to improve your react code from here.

Categories: Reactjs