React – Higher-Order Components (HOCs)

Higher-Order Components (HOCs) are a powerful pattern in React for reusing component logic. An HOC is a function that takes a component and returns a new component. HOCs allow you to add additional functionality to existing components without modifying their code.

Why Use Higher-Order Components?

HOCs are useful for:

  • Code reuse, logic, and bootstrap abstraction.
  • Rendering hijacking.
  • State abstraction and manipulation.
  • Props manipulation.

Creating an HOC

To create an HOC, you define a function that takes a component as an argument and returns a new component. The new component can add or modify the behavior of the original component.

Example: Logging Props with an HOC

Let’s create a simple HOC that logs the props of a component each time it renders.

Step 1: Create the HOC

Create a new file withLogging.js and add the following code:

import React from 'react';

function withLogging(WrappedComponent) {
  return class extends React.Component {
    componentDidUpdate(prevProps) {
      console.log('Current props:', this.props);
      console.log('Previous props:', prevProps);
    }

    render() {
      return <WrappedComponent {...this.props} />;
    }
  };
}

export default withLogging;

Explanation:

  1. Function Definition: withLogging is a function that takes a component WrappedComponent as an argument.
  2. New Component: The function returns a new component class that extends React.Component.
  3. Lifecycle Method: The componentDidUpdate lifecycle method logs the current and previous props to the console whenever the component updates.
  4. Render Method: The render method returns the original component WrappedComponent, passing down all the received props using {...this.props}.

Step 2: Create a Component to Use the HOC

Create a new file UserComponent.js and add the following code:

import React from 'react';

function UserComponent(props) {
  return (
    <div>
      <h1>User: {props.name}</h1>
    </div>
  );
}

export default UserComponent;

Step 3: Wrap the Component with the HOC

Modify the App.js file to include the wrapped component:

import React, { useState } from 'react';
import './App.css';
import UserComponent from './UserComponent';
import withLogging from './withLogging';

const UserWithLogging = withLogging(UserComponent);

function App() {
  const [name, setName] = useState('John Doe');

  return (
    <div className="App">
      <header className="App-header">
        <h1>React Higher-Order Component Example</h1>
        <UserWithLogging name={name} />
        <button onClick={() => setName(name === 'John Doe' ? 'Jane Doe' : 'John Doe')}>
          Change Name
        </button>
      </header>
    </div>
  );
}

export default App;

Explanation:

  1. Wrap the Component: The UserComponent is wrapped with the withLogging HOC to create UserWithLogging.
  2. State Management: The App component uses the useState hook to manage the name state.
  3. Event Handling: A button is provided to toggle the name state between “John Doe” and “Jane Doe”.
  4. Rendering: The UserWithLogging component is rendered with the current name state passed as a prop.

Summary

  • Higher-Order Components (HOCs): Functions that take a component and return a new component with additional functionality.
  • Code Reuse: HOCs are a pattern for reusing component logic and adding behavior to components.
  • Props and State Management: HOCs can manipulate props and state to modify the behavior of the wrapped component.

This example demonstrates how to create and use an HOC in React. The withLogging HOC adds logging functionality to any component, allowing you to see the component’s props each time it updates. HOCs are a powerful tool for enhancing the capabilities of your components in a reusable way.



Tutorials Deck

TutorialsDeck is striving to provide the best learning material on technical and non-technical subjects.

Languages

Web Technologies

Database

Trending Technologies

© 2024. All rights reserved.

Contact Us @ tutorialsdeck06@gmail.com