Higher Order Components(HOC)

Common useful utility functions in React Js

Ram Mohan
3 min readSep 18, 2020

GitHub: https://github.com/RamMohan222/react-hoc-utils

Sometimes we need some special Higher-Order Components or functions to compose the components with the dynamic or static properties. for that always we don’t need to depend on some other third-party packages we can build our own package with 2 to 5 lines of code and it will make our life easy. Here I have given some common useful higher-order components source code with a suitable example lets check them and start building your own library to your project.

1. withProps:
There is a situation we need to export our component with some external properties such a situation we can use the withProps this will wrap the component with whatever the properties we are passing through it.

Example:

Exporting the App component with external properties.

While rendering a component we can pass the props from parent to child component dynamically, But there is a situation we need to pass component itself as a property and it should wrap with some additional properties in that scenario we can use withProps to wrap the component with dynamic properties.

The normal way of passing props from parent to children.

<Component title="Title" action={()=>console.log("Some Action")} />

From the below example we are passing the Cell Component as property and it is wrapping with some additional properties with the help of withProps.

2. withContextProps:

In ReactJs recent release >=16.8 we can use more than one context by using useContext hook in functional components. But in class based components it is difficult to use more than one context. By using withContextProps HOC we can wrap more than one context with our component. It will convert all context props into component props. see the below code snippet for withContextProps HOC and it’s usage.

Example:

3. composeHOC
The below snippet is the source code for composeHOC.

It will compose more than on HOC’s into single HOC

Sometimes we need to wrap our component with more than one HOC's. The below code shows the App component is wrapping with more than one HOC and the same wrapping logic may be required in more than one component in our project. If we do in all places it's breaking the DRY principle and it looks odd too.

The App component wrapping with more than one HOC’s

Instead of writing the same logic, again and again, we can create a new reusable component by wrapping the common components with the help of composeHOC. check the below code for example.

Creates the new Reusable Higher Order Component by composing the common HOC’s.

Thanks to all.

--

--

Ram Mohan
Ram Mohan

Written by Ram Mohan

Love to code in Java| NodeJs | ReactJs and my new adoptions are Python and Go https://ram222mohan.com/