Higher-Order-Component(HOC) in React

AHMED M A
3 min readMar 28, 2021

HOC is a new feature in React to reuse components, HOC takes an old component and returns a new component for reused in

const Hoc=(WrappedComponent,data)

HOC takes two argument wrapped component and data and returns a new component. The component sends props to another component while the HOC component transfers the component to another component.

I did a simple web page to explain how we used Higher-Order-Component in react. I made three component movies, songs and tvshows , each component receives data and renders it. As you see below Songs component no need to declare a state inside the component to see all movies because he used the shared state which was declared in HOC, just he accessed the data by this.props.data coming from HOC.

In the next step, we will explain HOC component:

As you see above the HOC is a functional component that receives two arguments.

Wrapped component and data, and returns a new component. A returned component can be without a name like in the example “class extends Component” or you can add any name for the component like “class HocCom extends Component” it doesn’t make any change on the process, it will produce the same result.

The data that is passed as an argument will inject to state and then will inject to WrappedComponent as props which is passed to each component, As we mentioned WrappedCommponent one of this (TvShows or Songs or Movies) component that been imported in the App component then passed as an old component to make a process in HOC then will return new component for us :

const SongsHoc =Hoc(

Songs,data.songs

)

//HOC takes two argument old component Songs and data.songs , then HOC assigned to new variable component SongsHoc which will receive new HOC after made processing on it.

When we add song or add tvshow we will use the state to receive input of forms then we will use HOC’s state this.props.data to inject form input on it by using the push method in this example.

After this we push data will automatically rerender new this.props.data to display data on the screen.

Not all HOC’s are the same, sometimes HOC’s just accept one argument,

The most common use of HOC is a connect function that is used in react and redux considered HOC component.

const ConnectedComment=connect(commentSelector,commentActions)(CommentList);

Some Constraints in HOC

1- Ref not allowed to pass through HOC

2- HOC is not allowed to use inside the render method of a component.

Conclusion

Higher-Order-Component is like an abstraction that holds all the logic and shares it across many components, HOC will take two argument old component and data, then return new a component for us after making changes to state or other processes. HOC can take just one argument const NavbarWithRouter = withRouter(Navbar) 1.

https://github.com/engahmed10/higher-order-react-practice

--

--