Contents of React Interview Questions

Comprehensive collection of React interview questions and answers covering hooks, components, state management, and best practices.

Higher-Order Components (HOC) in React: What and Why

What is a Higher-Order Component (HOC)?

A Higher-Order Component (HOC) is an advanced React pattern used for reusing component logic. Technically, an HOC is a function that takes a component and returns a new component with enhanced or extended functionality.

Definition:
"A higher-order component is a function that takes a component and returns a new component."

Syntax Example:

const EnhancedComponent = higherOrderComponent(WrappedComponent);

In this pattern:

  • WrappedComponent is the original component.
  • higherOrderComponent is the HOC function.
  • EnhancedComponent is the new component created with additional capabilities.

Why Use HOCs?

HOCs help solve common challenges in React development, such as:

  1. Code Reusability:
    You can extract shared logic (e.g., fetching data, handling permissions) and apply it to multiple components without duplicating code.

  2. Separation of Concerns:
    HOCs separate "what" a component does (its logic) from "how" it looks (its UI). This makes components cleaner and easier to manage.

  3. Enhancing Components:
    HOCs allow you to add extra behaviors or props to components without modifying their internal implementation.

  4. Cross-Cutting Concerns:
    Features like logging, analytics tracking, or authentication checks can be implemented once in an HOC and reused across many components.


Example of a Simple HOC

Suppose we want to add a loading spinner to any component while it waits for data:

const withLoading = (Component) => { return function WithLoadingComponent({ isLoading, ...props }) { if (isLoading) { return <div>Loading...</div>; } return <Component {...props} />; }; }; // Usage const DataComponent = (props) => <div>{props.data}</div>; const DataComponentWithLoading = withLoading(DataComponent);

Now, DataComponentWithLoading will show "Loading..." when isLoading is true, otherwise, it renders DataComponent.


Important Notes About HOCs

  • HOCs should not mutate the original component. Always return a new component.
  • Static methods of the wrapped component are not automatically copied. You might need libraries like hoist-non-react-statics.
  • Naming convention: It’s common to name the new component by prefixing it with With or Enhanced, e.g., withAuth, withRouter.

Real-world Examples of HOCs

  • connect from react-redux to connect a component to the Redux store.
  • withRouter from react-router to inject routing-related props.

Conclusion

Higher-Order Components are a powerful pattern for reusing logic across multiple components in React. By abstracting shared behavior into HOCs, developers can write cleaner, more maintainable, and scalable applications.