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 use of create-react-class module. Official documentation
Of course you must first install it
npm install create-react-class
Here is a working example
import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')
let Clock = createReactClass({
getInitialState:function(){
return {date:new Date()}
},
render:function(){
return (
<h1>{this.state.date.toLocaleTimeString()}</h1>
)
},
componentDidMount:function(){
this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
},
componentWillUnmount:function(){
clearInterval(this.timerId)
}
})
ReactDOM.render(
<Clock/>,
document.getElementById('root')
)
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]);
};