Let's say we want to console.log each time the component mounts:
hocLogger.js
export default function hocLogger(Component) {
return class extends React.Component {
componentDidMount() {
console.log('Hey, we are mounted!');
}
render() {
return <Component {...this.props} />;
}
}
}
Use this HOC in your code:
MyLoggedComponent.js
import React from "react";
import {hocLogger} from "./hocLogger";
export class MyLoggedComponent extends React.Component {
render() {
return (
<div>
This component get's logged to console on each mount.
</div>
);
}
}
// Now wrap MyLoggedComponent with the hocLogger function
export default hocLogger(MyLoggedComponent);