Câu hỏi phỏng vấn Reactjs
Câu hỏi

What are Higher-Order Components (HOC) in React?

Câu trả lời

Higher-Order Components (HOCs) in React are a powerful pattern used for reusing component logic across multiple components. An HOC is essentially a function that takes a component and returns a new component, thereby enhancing the original component with additional properties or behavior without modifying its source code.

Definition and Purpose

A Higher-Order Component is a function that takes a component as an argument and returns a new component. It wraps the original component, providing additional functionality or data to it. This pattern is derived from React's compositional nature, where components can be used to build other components[1][2][3][4][5].

Usage and Examples

HOCs are commonly used for cross-cutting concerns, which are aspects of a program that affect other parts of the program and can be factored out into reusable code. Examples include:

  • Data fetching: An HOC can manage API calls and pass the fetched data as props to the wrapped component.
  • Authentication: An HOC can be used to check if a user is authenticated and conditionally render components based on the user's status.
  • Styling and theming: Components can be wrapped in HOCs to apply consistent styles or themes.

Implementation

To create an HOC, you define a function that takes a component (WrappedComponent) and returns a new component (EnhancedComponent). This new component can use React lifecycle methods, hooks, or other logic to inject new props into the WrappedComponent or manipulate its behavior.

Here’s a simple example of an HOC that adds additional props to a component:

function withExtraInfo(WrappedComponent) {
  return class extends React.Component {
    render() {
      return <WrappedComponent {...this.props} extraProp="someValue" />;
    }
  };
}

In this example, withExtraInfo is an HOC that takes a component (WrappedComponent) and returns a new component that renders the original component with an additional prop (extraProp)[1][2][3].

Benefits

  • Reusability: HOCs allow developers to reuse stateful logic across multiple components, reducing code dupli...
junior

junior

Gợi ý câu hỏi phỏng vấn

middle

What's wrong with using Context in React?

senior

Can you force a React component to rerender without calling setState ?

middle

Why do class methods need to be bound to a class instance?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào