38. What are Higher-Order Components (HOCs) in React?
medium

Higher-Order Components (HOCs) are a design pattern in React that allows you to wrap existing components with additional functionality without modifying their code.

Explanation of Key Concepts

  • HOC: A function that takes another component as an argument and returns a new component with added props, logic, or behavior.
  • Wrapped Component: The original component being wrapped by the HOC.
  • Enhanced Component: The new component returned by the HOC, which wraps the original component with additional functionality.

Step-by-Step Solution

To create a Higher-Order Component (HOC), follow these steps:

  1. Receive a component as input: The HOC takes another React component (WrappedComponent) as an input parameter.
  2. Enhance the component: Add new props, logic, or functionality to the wrapped component.
  3. Return a new functional component: The new component renders the original, passing through any necessary props along with the new ones.

Example: Creating and Using a HOC

import React from 'react';

// HOC that adds an extra prop
const withExtraProps = (WrappedComponent) => {
  return (props) => <WrappedComponent {...props} extraProp="value" />;
};

// Component to be wrapped
const MyComponent = (props) => {
  return <div>Extra prop: {props.extraProp}</div>;
};

// Enhanced version of MyComponent
const EnhancedComponent = withExtraProps(MyComponent);

// Usage
const App = () => {
  return <EnhancedComponent />;
};

Common Use Cases

HOCs are useful for:

  • Reusing logic across multiple components
  • Adding common behaviors like logging, authentication, or theming
  • Separating concerns and keeping components focused and small

Best Practices

  • Do not mutate the original component
  • Use descriptive names (e.g., withAuth, withLogger)
  • Use HOCs sparingly to avoid complexity
  • Avoid nesting HOCs deeply (can lead to "wrapper hell")

Alternatives

In modern React codebases, Custom Hooks are often preferred for logic reuse. However, understanding HOCs is still essential for working with legacy code and some libraries.

Conclusion

HOCs are a powerful abstraction for sharing logic between components in React. They promote code reuse, composability, and separation of concerns, but should be used judiciously to avoid complexity.