Let's Learn all about react HOC.
In react.js HOC which refers to the Higher Order Component is a design pattern used to enforce better component reusability and it's also a best practice to write your cross-cutting concerns of your application inside HOC.
Though we have other options available in React to handle this specific need like mixins, but it creates more trouble than it's worth.
HOC is purely based on a javascript higher-order function which accepts a function as an argument and returns the same function as output without mutating it. so there might be a question of why we need it then? so here are several scenarios listed as follows:
Functional Composition.
Abstraction and code reuse.
Callbacks and event handling.
functional programming paradigm.
likewise in react, we use HOC where we pass a component as an argument to another component, which returns the component without any side effect.
Here is an exaple of Higher Order Component:
In this example, withLogger is a Higher Order Component that takes a component (wrappedComponent) as an argument. It returns a new component that logs a message when it mounts and renders the wrappedComponent with all the original props passed to it.
By wrapping MyComponent with withLogger, we create a new component called EnhancedComponent. When EnhancedComponent is mounted, it will log the message "Component MyComponent mounted."