Higher Order Functions

Higher Order Functions

Table of contents

Intro

  1. 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.

  2. 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

  3. 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'));
  1. In the example above, withLogger is a higher-order function that takes a component (WrappedComponent) as an argument and returns a new component (WithLogger). The WithLogger component adds logging functionality by logging when the component is mounted and unmounted.

  2. The EnhancedComponent is the result of calling the withLogger function with the MyComponent. When rendered, the EnhancedComponent will have the additional logging functionality provided by the WithLogger component.

  3. 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.