Higher-Order Components

A Higher-Order Component (HOC) is a function that accepts a component and returns a new component with additional behavior. It is a composition pattern that helps reuse logic across multiple components without modifying their implementations.

A Higher-Order Component is not a React component by itself. Instead, it is a function whose input is a component and whose output is another component that wraps or enhances the original one. The wrapped component typically receives extra props, data, or behavior.

HOCs are useful when the same cross-cutting functionality is needed in many places. Common examples include authentication checks, permission handling, analytics, feature flags, and connecting components to external data sources. The original component can stay focused on rendering while the HOC manages the shared concern.

A well-designed HOC forwards unrelated props to the wrapped component instead of filtering them out. It should also avoid mutating the original component. Returning a new wrapper preserves predictable behavior and allows multiple HOCs to be composed together.

Although HOCs remain common in existing codebases, modern React applications often prefer custom hooks for sharing stateful logic between function components. Understanding HOCs is still important because many libraries and legacy projects use them extensively.

Key points

Interview questions

Why is mutating the wrapped component discouraged?

Mutating the original component introduces hidden side effects and makes behavior harder to reason about. Returning a new wrapper keeps the original component unchanged and supports predictable composition. This also makes multiple HOCs easier to combine safely.

What is a Higher-Order Component?

A Higher-Order Component is a function that accepts a component and returns a new component with additional behavior. It is a composition technique rather than a special React feature. The wrapped component typically receives extra props or functionality while remaining reusable and focused on presentation.

Why should a HOC forward props?

Forwarding props allows the wrapped component to continue receiving the values expected by its callers. Without forwarding, the wrapper may accidentally hide required inputs or reduce flexibility. The HOC should usually inject only the additional data it owns while passing everything else through unchanged.

When would you choose a HOC instead of a custom hook?

A HOC is useful when integrating with APIs or libraries that already expose HOCs or when behavior must wrap an entire component. In new function-component code, custom hooks are often simpler for sharing stateful logic. Existing architecture, interoperability, and readability should guide the choice.