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:
- Create a Function: Define a function that takes a component as an argument.
- Return a New Component: Inside this function, return a new component that renders the original component with additional props or logic.
- 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);