codewithgigi logo
codewithgigi logo
react higher-order components

React high order components explained

The react website defines or explains react higher-order components as

"a higher-order component is a function that takes a component and returns a new component."

But what exactly does this mean? And why do we need this pattern? The main and only reason is realy for code re-use. Or as we say in software keep your code DRY "Don't repeat yourself".

Say we have a component that fetches some data and displays some data. The logic simply fetches data from some external api, then stores the results in our componet state and renders and displays that data.

Now if we have multiple components that may need to execute the same or very similar logic, we can repeat or copy that code to our new componet. Or better yet we can abstract out the logic into a higher-order component so we can re-use it in other components.

Let's look at the below examples.

Code examples
Watch the video demo