Higher Order Component in React: What It Is and How It Works
Higher Order Component (HOC) in React is a function that takes a component and returns a new enhanced component. It helps reuse logic by wrapping components with extra features without changing their original code.How It Works
Think of a Higher Order Component like a gift wrapper for a present. You have a simple gift (a React component), and the wrapper adds decorations or extra features without changing the gift itself. The HOC takes your original component, adds some new behavior or data, and then gives you back a new component that looks and works like the original but with added powers.
This works by creating a function that accepts a component as input and returns a new component. Inside, it can add state, side effects, or props before rendering the original component. This way, you keep your components clean and focused, while sharing common logic easily.
Example
This example shows a simple HOC that adds a loading message before showing the wrapped component.
import React, { useState, useEffect } from 'react'; // Higher Order Component that adds loading behavior function withLoading(Component) { return function WrappedComponent(props) { const [loading, setLoading] = useState(true); useEffect(() => { const timer = setTimeout(() => setLoading(false), 2000); return () => clearTimeout(timer); }, []); if (loading) { return <p>Loading...</p>; } return <Component {...props} />; }; } // Simple component to wrap function Hello() { return <h1>Hello, world!</h1>; } // Wrapped component with loading const HelloWithLoading = withLoading(Hello); export default function App() { return <HelloWithLoading />; }
When to Use
Use Higher Order Components when you want to share common logic or behavior across many components without repeating code. For example, you can use HOCs to add loading states, authentication checks, theming, or data fetching to multiple components.
This keeps your components simple and focused on their main job, while the HOC handles the shared tasks. It is especially useful in large apps where many components need similar enhancements.
Key Points
- A Higher Order Component is a function that takes a component and returns a new component.
- It helps reuse logic by wrapping components with extra features.
- HOCs do not modify the original component but create a new enhanced one.
- Common uses include adding loading states, authentication, or theming.
- They keep components clean and focused on their main purpose.