paint-brush
Mastering Higher Order Components (HOCs) in Reactby@ljaviertovar
19,979 reads
19,979 reads

Mastering Higher Order Components (HOCs) in React

by L Javier TovarOctober 13th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Higher Order Components (HOCs) in React are a powerful tool for enhancing component capabilities without sacrificing code clarity. They enable you to share functionalities among multiple components, promoting reusability, separation of concerns, and code abstraction. This blog explores the concept of HOCs, their benefits, and two implementation approaches - passing the original component as a parameter and the "Render Props" approach. You'll gain insights into when to use each approach and see practical examples. Harness the power of HOCs to supercharge your React applications and improve code maintainability.
featured image - Mastering Higher Order Components (HOCs) in React
L Javier Tovar HackerNoon profile picture

As React developers, we often encounter scenarios where we need to share functionalities among multiple components. One of the options to address these cases is using Higher Order Components, also known as HOCs.


Higher Order Components (HOCs) are a tool that allows you to extend your component’s capabilities without sacrificing code clarity or creating unnecessary redundancies.


In this blog, we will delve into what HOCs are, why they are helpful, and how to create and use them in your React applications.


Understanding Higher Order Components (HOCs)

Higher-order components are a design pattern in React where a function takes a component as an argument and returns an enhanced new component.


In simpler terms, HOCs are functions that wrap existing components, providing them with additional props or behaviors.


The main benefit of HOCs is that they enable us to extend the functionality of multiple components without repeating the same code in each of them. This promotes code reuse and enhances the maintainability of your React applications.


Benefits of Higher Order Components

  • Reusability: HOCs allow you to encapsulate shared functionalities and apply them to multiple components, promoting code reuse.


  • Separation of Concerns: HOCs help maintain separate responsibilities, enabling your components to focus on their specific tasks.


  • Code Abstraction: HOCs abstract common logic from components, making them more concise and easier to understand.


  • Composability: You can combine various HOCs to compose complex functionalities into your components.


Approaches to HOCs

There are two approaches to implementing HOCs: the Approach of Passing the Original Component as a Parameter and the “Render Props” Approach.


The choice between these approaches depends on the use case and your personal preferences. Both approaches have their advantages and disadvantages.


Passing the Original Component as a Parameter

Pros:

  • More straightforward. The wrapped component is directly passed as a parameter to the HOC function.

  • Less nesting in the component tree.


    Cons:

  • Less flexible in terms of how the wrapped component is rendered.

  • It may be less intuitive when dealing with multiple chained HOCs.


Render Props Approach

Pros:

  • Greater flexibility in component composition and rendering.
  • Useful when you want the wrapped component to have more control over handling certain aspects, such as events.


Cons:

  • This may result in more verbose and nested code when using multiple Render Props.
  • Might require a higher understanding of React patterns by developers.


The choice depends on the context and your preferences in terms of readability, control, and flexibility. In general, both approaches are valid and widely used within the React community.

Consider the specific use case and choose the approach that best fits your needs and your team’s coding style.


HOC Examples

Let’s consider an application that needs to track click events across various components. Instead of adding click event tracking to each component, we can create a HOC that registers click events and then applies it to the required components.

Passing the Original Component as a Parameter

import React from 'react';

// HOC ClickTrackingHOC
const withClickTracking = (WrappedComponent) => {
  return (props) => {
    const handleClick = () => {
      console.log('Click tracked:', props.trackingInfo);
    };

    return (
      <div onClick={handleClick}>
        <WrappedComponent {...props} />
      </div>
    );
  };
};

// Original component
const Button = (props) => {
  return <button>{props.label}</button>;
};

// Applying the HOC to the original component
const ButtonWithClickTracking = withClickTracking(Button);

const App = () => {
  return (
    <div>
      <h1>HOC Example</h1>
      <ButtonWithClickTracking label="Click Me" trackingInfo="Button 1" />
      <ButtonWithClickTracking label="Click Me Too" trackingInfo="Button 2" />
    </div>
  );
};

export default App;


Render Props Approach

import React from 'react';

// HOC ClickTrackingHOC
const withClickTracking = (props) => {
  const handleClick = () => {
    console.log('Click tracked:', props.trackingInfo);
  };

  return (
    <div onClick={handleClick}>
      {props.children}
    </div>
  );
};

// Original component
const Button = (props) => {
  return <button>{props.label}</button>;
};

const App = () => {
  return (
    <div>
      <h1>Render Props Example</h1>
      // Applying the HOC to the original component
      <withClickTracking trackingInfo="Button 1">
        <Button label="Click Me" />
      </withClickTracking>
      <withClickTracking trackingInfo="Button 2">
        <Button label="Click Me Too" />
      </withClickTracking>
    </div>
  );
};

export default App;


In these examples, we’ve added a prop called trackingInfo to the ButtonWithClivkTracking component. This prop is used in the handleClick function within the HOC to display which button has been clicked.


When one of the buttons is clicked, the onclick event captures the click and logs the corresponding tracking information to the console. Each button has its own tracking information passed as a prop to the wrapped component (Button).


This demonstrates how props can effectively pass through HOCs to enhance component functionality.

Conclusion

In conclusion, Higher-Order Components are a powerful tool in React that facilitates code reuse and promotes clean and maintainable code. By creating HOCs, you can efficiently share functionalities among different components, making your React applications more efficient and easier to maintain.


Read more:



Also published here.

Want to connect with the Author?

Love connecting with friends all around the world on X.