Today’s Offer Enroll today and get access to premium content.
App Store Google Play
Advanced

What are higher-order components (HOCs) in React?

Higher-order components (HOCs) are advanced patterns in React that allow you to reuse component logic. An HOC is a function that takes a component and returns a new component with enhanced functionalities.

To create an HOC:

  1. Create a Function: Define a function that takes a component as an argument.
  2. Return a New Component: Inside this function, return a new component that renders the original component with additional props or logic.
  3. Usage: HOCs can be used for cross-cutting concerns like logging, access control, or data fetching.

Example of an HOC:

const withLogging = (WrappedComponent) => { return (props) => { console.log('Rendering:', WrappedComponent.name); return <WrappedComponent {...props} />; }; }; const MyComponent = () => <div>My Component</div>; const EnhancedComponent = withLogging(MyComponent);