Using react higher order component

posted on 28 June 2018

When you start to work with lots of React components, and you realised alot of component patterns are the same, then you want to reuse these component patterns which is where Higher Order Component(HOC) kicks in. Think of HOC as higher order function:

usually you write function in Javascript:

Higher order function basically is just a function returns a function.

lets take an example at React Components:

Here what we saying is create a component called Dropdown, and takes in another component called DropdownMenuItemComponent, and when toggle it should open the menu… A typical dropdown menu pattern.

Lets say you want to keep these patterns/methods as parent component, example toggle etc… or you want to pass in some props and change methods based on the props then HOC(higher order component will be really useful).

Its pretty easy to create a HOC, same as higher order function, we should create a function and return a Component method.

and you can use the component by passing the component into this function.

lets say you want to pass in some properties from component to dropdownHOC function, use currying…

and now you can passing the props like this: