Higher Order Component implementation in React

Higher Order Component implementation in React

React has multiple ways to share data or stateful logic between components and Higher-order components are one of them. It can also be shared with render props, and context API as well. Also, there are multiple hooks such as useReducer, useContext, and so on.

Higher order function is basically a function that can take another function as a parameter and produces a resultant output. Some of the benefits of the HOCs are as follows:

  1. HOCs do not modify or mutate the component but produce a new one.

  2. It works like a pure function and does not cause any other side effects.

  3. They provide a way for reusing the code when ES6 classes are used.

  4. They don't have a method name clashing if two components are using same one.

    Also, there are some limitations as well which are as follows:

    1. Wrapping multiple HOCs to a single component increases the tree structure and can cause debugging difficult.

    2. It can hoist the static methods from the wrapped components.

So, in the example, there are three components that have a common state, and manipulation of that takes place through the higher-order component.

In this example, Increment and decrement functions are defined in the HOC and even the state is also defined there itself which again is passed to others through props.

That's it, for now, hope you liked the code snippet and some of the important points about the HOCs. Happy Coding! Thank you.

Did you find this article valuable?

Support Ajinkya Chanshetty's Blog by becoming a sponsor. Any amount is appreciated!