Home > Web Front-end > JS Tutorial > body text

Higher-Order Components (HOCs) in React

DDD
Release: 2024-09-30 12:32:02
Original
549 people have browsed it

Higher-Order Components (HOCs) in React

Higher-Order Components (HOCs) in React are functions that take a component and return a new component with enhanced functionality. They allow you to reuse logic across multiple components without duplicating code.

Here's a basic example of a HOC:

import React from 'react';

// A Higher-Order Component
function withExtraInfo(WrappedComponent) {
  return function EnhancedComponent(props) {
    return (
      <div>
        <p>This is extra info added by the HOC!</p>
        <WrappedComponent {...props} />
      </div>
    );
  };
}

// A regular component
function MyComponent() {
  return <p>This is my component!</p>;
}

// Wrap the component with the HOC
const EnhancedMyComponent = withExtraInfo(MyComponent);

function App() {
  return <EnhancedMyComponent />;
}

export default App;
Copy after login

Key points about HOCs:

  • Purpose: Used to add reusable logic to components (e.g., logging, permissions, etc.).
  • Pure functions: They don't modify the original component but return a new one.
  • Common use cases: Authorization, theme switching, data fetching, etc.

While HOCs were more commonly used before the introduction of React hooks, they are still useful in many cases.

The above is the detailed content of Higher-Order Components (HOCs) in React. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!