Appearance
Higher Order Component
A Higher Order Component (HOC) is a React pattern that wraps a component with another often re-useable component to add additional functionality.
At a high level the structure of a HOC looks like:
js
function withExtraFunction(WrappedComponent) {
return function EnhancedComponent(props) {
// do extra functionalities
return <WrappedComponent {...props} />;
};
}
// To use
const EnhancedComponent = withExtraFunction(Component);Some common examples of HOC in React includes:
- withAuth
- withLogger
- withTheme
- withRouter
For example in react-router this is the implementation for withRouter
js
import {
useLocation,
useNavigate,
useParams,
} from "react-router-dom";
function withRouter(Component) {
function ComponentWithRouterProp(props) {
let location = useLocation();
let navigate = useNavigate();
let params = useParams();
return (
<Component
{...props}
router={{ location, navigate, params }}
/>
);
}
return ComponentWithRouterProp;
}Any component that's wrapped with withRouter will gain access to the additional router props.
js
function App(props) {
// props.router added by withRouter
//...
}
const AppWithRouter = withRouter(App)HOC is useful for reusing small chunks of logic across many different components. Other similar patterns include Render Props and Hooks.