React Interview Questions
React.js
FrontendWeb DevelopmentQuestion 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
- Code Reuse: Sharing common functionality between multiple components.
- Manipulating Props: Injecting additional props or modifying existing ones.
- Conditional Rendering: Adding conditional logic for rendering.
- 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.
- 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;
- 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;
- 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 atimestamp
prop to the wrappedDisplay
component.Display
is the original component that displays a message and the current timestamp.EnhancedDisplay
is the result of wrappingDisplay
withwithTimestamp
, providing it with the additionaltimestamp
prop.
Advantages
- Separation of Concerns: HOCs allow you to separate logic from presentation.
- Reusability: They enable the reuse of common functionality across multiple components.
- Enhanced Readability: By abstracting complex logic into HOCs, the main component code becomes cleaner and more readable.
Considerations
- Props Collision: Be cautious of naming collisions with props. Ensure unique prop names to avoid conflicts.
- Performance: Multiple layers of HOCs can lead to performance issues due to the additional render cycles. Optimize and use memoization where appropriate.
- 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.