A Higher Order Component (HOC) is a design pattern in React that allows you to reuse and share logic between components. HOCs are not part of the React API, but a pattern that emerges from React's compositional nature.
A Higher Order Component is a function that takes a component and returns a new component with added or enhanced functionality.
Here's a simple example of a HOC that adds a simple login feature to a component:
In this example, the withLogin HOC takes the LoginButton component as an argument and returns a new component with the added isLoggedIn and toggleLogin state and methods. The original LoginButton component is wrapped by the HOC and receives the added props.
You can use the HOC just like any other component, and it will add the new functionality to the wrapped component.
Note that HOCs are a powerful pattern and should be used with caution, as they can make your code more complex and harder to understand. It's best to use HOCs when you need to share logic between multiple components, rather than using them for every component.
In this example, the withTitle HOC takes the MyComponent component as an argument and returns a new component that wraps the original component in a div and adds a title, specified by the title prop.