Table of contents
Intro
In React, higher-order functions (HOCs) are a common pattern used to enhance component functionality and reuse code. HOCs are functions that take a component as an argument and return a new enhanced component. They allow you to add additional props, modify behavior, or wrap the component with additional functionality.
It is basically used to enhance the functionality of the original card ie the original component will be added some styling based on what we mention in react
Here's an example of a higher-order function in React:
import React from 'react';
const withLogger = (WrappedComponent) => {
class WithLogger extends React.Component {
componentDidMount() {
console.log('Component is mounted');
}
componentWillUnmount() {
console.log('Component is unmounted');
}
render() {
return <WrappedComponent {...this.props} />;
}
}
return WithLogger;
};
// Usage:
const MyComponent = (props) => {
return <div>Hello, {props.name}!</div>;
};
const EnhancedComponent = withLogger(MyComponent);
// Render the enhanced component
ReactDOM.render(<EnhancedComponent name="John" />, document.getElementById('root'));
In the example above,
withLogger
is a higher-order function that takes a component (WrappedComponent
) as an argument and returns a new component (WithLogger
). TheWithLogger
component adds logging functionality by logging when the component is mounted and unmounted.The
EnhancedComponent
is the result of calling thewithLogger
function with theMyComponent
. When rendered, theEnhancedComponent
will have the additional logging functionality provided by theWithLogger
component.Higher-order functions are widely used in React to achieve code reusability, separation of concerns, and to add additional features to components without modifying their original implementation.