React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 16

What is a higher-order component (HOC) in React?

Answer:

A Higher-Order Component (HOC) in React is a pattern used to enhance or modify the behavior of a component by wrapping it with another component. HOCs are not part of the React API itself but rather a pattern that emerges from React's compositional nature.

Definition

A Higher-Order Component is a function that takes a component and returns a new component with enhanced behavior.

Syntax

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Purpose

HOCs are used for code reuse, logic abstraction, and side-effect management. They can add additional props, state, or lifecycle methods to the wrapped component.

Common Use Cases

  1. Code Reuse: Sharing common functionality between multiple components.
  2. Manipulating Props: Injecting additional props or modifying existing ones.
  3. Conditional Rendering: Adding conditional logic for rendering.
  4. Side-Effect Management: Handling side effects like data fetching or subscriptions.

Example: Adding a Timestamp

Let's create an HOC that adds a timestamp to a wrapped component.

  1. Create the HOC:
import React from 'react';

function withTimestamp(WrappedComponent) {
  return class extends React.Component {
    render() {
      const currentTime = new Date().toLocaleTimeString();
      return <WrappedComponent {...this.props} timestamp={currentTime} />;
    }
  };
}

export default withTimestamp;
  1. Create a Component to Wrap:
import React from 'react';

function Display(props) {
  return (
    <div>
      <p>{props.message}</p>
      <p>Current Time: {props.timestamp}</p>
    </div>
  );
}

export default Display;
  1. Wrap the Component with the HOC:
import React from 'react';
import withTimestamp from './withTimestamp';
import Display from './Display';

const EnhancedDisplay = withTimestamp(Display);

function App() {
  return (
    <div>
      <EnhancedDisplay message="Hello, World!" />
    </div>
  );
}

export default App;

In this example:

  • withTimestamp is the higher-order component that adds a timestamp prop to the wrapped Display component.
  • Display is the original component that displays a message and the current timestamp.
  • EnhancedDisplay is the result of wrapping Display with withTimestamp, providing it with the additional timestamp prop.

Advantages

  1. Separation of Concerns: HOCs allow you to separate logic from presentation.
  2. Reusability: They enable the reuse of common functionality across multiple components.
  3. Enhanced Readability: By abstracting complex logic into HOCs, the main component code becomes cleaner and more readable.

Considerations

  1. Props Collision: Be cautious of naming collisions with props. Ensure unique prop names to avoid conflicts.
  2. Performance: Multiple layers of HOCs can lead to performance issues due to the additional render cycles. Optimize and use memoization where appropriate.
  3. Debugging: HOCs can make debugging more challenging due to the additional layers of abstraction. Using meaningful names for HOCs and leveraging React DevTools can help mitigate this.

Conclusion

Higher-Order Components are a powerful pattern in React for enhancing components with additional behavior. By wrapping components, HOCs provide a way to share reusable logic, manage side effects, and manipulate props, leading to more modular and maintainable code.

Recent job openings