erojas.devertek.io logo
Higher-Order Component (HOC) Pattern in React

What is a Higher-Order Component?

A Higher-Order Component (HOC) is a function that takes a component as an argument and returns a new component. HOCs are used to add additional functionality or modify the behavior of existing components without altering their core logic.

1const withExtraFunctionality = (WrappedComponent) => {
2  return (props) => {
3    // Add extra behavior or logic here
4    return <WrappedComponent {...props} />;
5  };
6};

Why Use HOCs?

HOCs provide several benefits:

  • Code Reusability: Avoid duplicating logic by encapsulating it in a reusable wrapper.

  • Separation of Concerns: Keep core component logic separate from auxiliary behavior.

  • Improved Maintainability: Centralize shared functionality in one place.

  • Composability: Combine multiple HOCs to create powerful, feature-rich components.

Example 1: Logging Props

This HOC logs the props passed to a component:

1const withLogger = (WrappedComponent) => {
2  return (props) => {
3    console.log("Props:", props);
4    return <WrappedComponent {...props} />;
5  };
6};
7const MyComponent = (props) => <div>{props.message}</div>;
8const EnhancedComponent = withLogger(MyComponent);
9// Usage
10<EnhancedComponent message="Hello, HOC!" />;

Best Practices

  • Don’t Overuse: Avoid nesting too many HOCs, as it can make the code harder to debug.

  • Pass Props Appropriately: Always pass props through to the wrapped component.

Name Wrapped Components: Use display names to make debugging easier.

1const withLogger = (WrappedComponent) => {
2  const EnhancedComponent = (props) => <WrappedComponent {...props} />;
3  EnhancedComponent.displayName = `withLogger(${
4    WrappedComponent.displayName || WrappedComponent.name || "Component"
5  })`;
6  return EnhancedComponent;
7};
8

Consider using other methods

1import React, { createContext, useContext } from "react";
2// Create a context
3const UserContext = createContext();
4// Provider component
5const UserProvider = ({ children }) => {
6  const user = { name: "John Doe", email: "john.doe@example.com" };
7  return <UserContext.Provider value={user}>{children}</UserContext.Provider>;
8};
9// Component consuming the context
10const UserProfile = () => {
11  const user = useContext(UserContext);
12  return (
13    <div>
14      <h1>{user.name}</h1>
15      <p>{user.email}</p>
16    </div>
17  );
18};
19// Usage
20const App = () => (
21  <UserProvider>
22    <UserProfile />
23  </UserProvider>
24);
25export default App;

Conclusion

The Higher-Order Component pattern is a powerful tool in React for creating reusable, maintainable, and composable components. While modern React has introduced hooks that can sometimes simplify logic sharing, HOCs remain a vital part of the React ecosystem. Use them wisely to unlock the full potential of your React applications!