Day 07: Higher Order Components (HOCs)

Day 07: Higher Order Components (HOCs)

·

1 min read

#100DaysOfCode

Day 07: Higher Order Components (HOCs)

Learned about the HOCs in react, which is a function that takes a component and returns a new component. Due to react hooks, HOCs are not used commonly for reusing logic.

HOCs stem from the concept of HOFs (Higher Order Functions), which whenever taking a function as an argument, returns a function with its return statement.

A Higher-Order Component comes always with the prefix with (same as a React Hook comes always with the prefix use). Example: withHigherOrderComponent

We can use a HOC to pass the props of some component to the input component, to make it enhanced. We can also add conditional renderings on the passed props to handle edge cases.

As HOCs are functions, we can also pass configuration arguments too. Like passing a custom error message to it. To configure HOC, wrap it with a function passing a configuration object as an argument to it.

What's great about Higher-Order Components is that they are just functions that allow you to split functionality into multiple functions.

Code

https://github.com/moazamdev/100DaysOfCode/tree/main/src/components/day7

Article Source

https://www.robinwieruch.de/react-higher-order-components/

#reactjs #frontenddev #webdev #javascript #learnreact