I'm converting class-based Heading component to functional component but that component is using 3 lifecycle hooks componentDidMount, componentWillUnmount and componentDidUpdate.
I replaced componentDidMount and componentWillUnmount but how to replace componentDidUpdate? It is comparing updated prop value with old prop value.
App Component:
import React, { Component } from "react";
import { Heading } from "./components/Heading";
import { HeadingHook } from "./components/HeadingHook";
export class App extends Component {
state = {
flag: false,
mountUnmount: true
};
toggleChangeFlag = () => {
if (this.state.mountUnmount) {
this.setState({
flag: !this.state.flag
});
}
};
toggleMountUnmount = () => {
this.setState({
flag: false,
mountUnmount: !this.state.mountUnmount
});
};
render() {
return (
<>
<div>
<p>Controls :</p>
<button onClick={this.toggleChangeFlag}>Change Flag</button>
<button onClick={this.toggleMountUnmount}>Mount & Unmount</button>
</div>
{this.state.mountUnmount && <Heading flag={this.state.flag} />}
{/* Comment above line to use useEffect Heading Component */}
{/* {this.state.mountUnmount && <HeadingHook flag={this.state.flag} />} */}
</>
);
}
}
Class-based Heading Component:
import React, {Component} from 'react';
export class Heading extends Component {
handleProps() {
if (this.props.flag) {
alert(this.props.flag);
} else {
alert(this.props.flag);
}
};
componentDidMount() {
this.handleProps();
}
componentWillUnmount() {
this.handleProps();
}
componentDidUpdate(prevProps) {
if (this.props.flag !== prevProps.flag) {
this.handleProps();
}
}
render() {
return <h1>Hello World!</h1>;
}
}
useEffect Heading Component:
import React, { useEffect } from "react";
export const HeadingHook = (props) => {
const handleProps = () => {
if (props.flag) {
alert(props.flag);
} else {
alert(props.flag);
}
};
useEffect(() => {
handleProps();
return () => {
handleProps();
};
});
return <h1>Hello World!</h1>;
};