Instead of writing my components inside a class, I\'d like to use the function syntax instead.
How do I override componentDidMount
, componentWillM
You can make your own "lifecycle methods" using hooks for maximum nostalgia.
Utility functions:
import { useEffect, useRef } from "react";
export const componentDidMount = handler => {
return useEffect(() => {
return handler();
}, []);
};
export const componentDidUpdate = (handler, deps) => {
const isInitialMount = useRef(true);
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false;
return;
}
return handler();
}, deps);
};
Usage:
import { componentDidMount, componentDidUpdate } from "./utils";
export const MyComponent = ({ myProp }) => {
componentDidMount(() => {
console.log("Component did mount!");
});
componentDidUpdate(() => {
console.log("Component did update!");
});
componentDidUpdate(() => {
console.log("myProp did update!");
}, [myProp]);
};