Skip to content
Today's Tech Byte: Higher-order components in modern world

Today's Tech Byte: Higher-order components in modern world

Posted on:November 13, 2023

This was more like a history lesson, because High order components are rarely used now, but we may still find them in some libraries.

As the name suggests, a higher-order component is a component that takes another component as an argument and returns a new component. It is a function that takes a component and returns a new component.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

High order components can be used for:

const withUser = (Component) => {
  return (props) =>  {
     const onClick = () => {
            console.log('clicked');
            onClick();
     };
      return <Component {props} onClick={onClick} />;
  };
};
export const withUser = Component => {
  return ({ id, ...props }) => {
    // do something whenever id changes
    useEffect(() => {
      console.log("id changed");
    }, [id]);
    // and pass back props intact
    return <Component {...props} />;
  };
};
const withUser = Component => {
  return ({ id, ...props }) => {
    const handleMouseEnter = event => {
      event.preventDefault();
    };
    return (
      <div onMouseEnter={handleMouseEnter}>
        <Component {...props} />
      </div>
    );
  };
};

That’s it for today’s tech byte.

If you have any suggestions or questions, feel free to reach out to me on Twitter or LinkedIn.

P.S. this post is inspired by the book, but it’s not a summary of it. I’m just sharing what I learned from it. If you want to learn more about React, I highly recommend you to read it.