Higher Order Functions In React

Author - Venkat

About this article - Description


What are Higher Order Components?

A Higher Order Components is a component that takes another component as an input and returns an enhanced version of the input component.

import React from "react";
 
// Higher Order Component (HOC)
const withBorder = (WrappedComponent) => {
  return (props) => (
    <div style={{ border: "2px solid blue", padding: "10px" }}>
      <WrappedComponent {...props} />
    </div>
  );
};
 
// Simple Component
const Message = ({ text }) => <h2>{text}</h2>;
 
// Wrap Message component with HOC
const MessageWithBorder = withBorder(Message);
 
const App = () => {
  return <MessageWithBorder text="Hello, HOC!" />;
};
 
export default App;

By using Higher Order Components we can reuse logic across components, add extra functionalities to existing components.