Introduction Higher Order Component is a pattern in React to reuse the functionality inside a component without rewriting the same code. It is not something related to React but a functionality came into emergence due to the component nature of React. HOC is not a component but a function that takes in a component and returns another component with some modifications to the input component.
How does HOC work? Let’s take a simple example. Suppose we have a class component[Child.js] for incrementing and decrementing the age as per button click. And we want to have another property to display a greeting message as we open the page. This greeting message is not a part of the class component but is passed as a property from the HOC. The snippet of the component where we wrote our HOC is shown below.
Component performing as HOC
The withAddedFunctionality component shown above works as HOC. It takes a component[WrappedComponent] as argument, adds a new property[greeting] to it and returns the updated component[HigherOrderComponent]. Now we can pass any component in place of WrappedComponent and the property greeting will be added as a property of the modified WrappedComponent. Below is a snippet of the syntax.
We wrote this code inside the Child.js file and passed Child component as the input to the HOC and we have the updatedChild component with an additional property “greeting”. Summary HOC is good as it allows us to introduce an added functionality without rewriting the same code in all different components. When used wisely it can create wonders in terms of code-modularity and simplicity. One common example of HOC is the connect function which we use to connect a third party redux store with our class component. We will cover that in the subsequent blogs. Below is a snippet of how connect looks like. NOTE: You can access the source code in this location – https://github.com/Titashr/my_react_app
Kommentare