August 30, 2023
O. Wolfson
In React and some other UI frameworks, a Higher-Order Component (HOC) is a pattern that is used to share common functionality between components without repeating code. A Higher-Order Component is a function that takes a component and returns a new component with additional props or behavior.
The concept of a "higher-order" function or component comes from functional programming. In functional programming, higher-order functions are functions that take functions as arguments, return functions, or both. Similarly, a Higher-Order Component (HOC) is a function that takes a component and returns a new component with some added or modified functionalities.
Here's a simple example that demonstrates how a Higher-Order Component can work:
jsx// A simple Higher-Order Component that adds a greeting prop
function withGreeting(WrappedComponent) {
return function EnhancedComponent(props) {
return <WrappedComponent {...props} greeting="Hello, " />;
};
}
// A basic component
function User(props) {
return (
<div>
{props.greeting} {props.name}!
</div>
);
}
// Using the Higher-Order Component
const UserWithGreeting = withGreeting(User);
// Usage
<UserWithGreeting name="John" />;
When this is rendered, it would produce: "Hello, John!"
props since your HOC might be adding props that the WrappedComponent is already receiving from its parent.Understanding Higher-Order Components can greatly help in structuring and organizing your React applications for scalability and reusability.