The component first renders with “red” as the favorite color. After mounting, a timer updates the state, changing the color to “yellow”. This triggers the update phase, and componentDidUpdate is called. It then writes a message to the empty DIV.
Example:
The componentDidUpdate method is invoked after the update has been rendered in the DOM.
class Header extends React.Component {
constructor(props) {
super(props );
this.state = {favoritecolor: "red"};
}
componentDidMount() {
setTimeout(() => {
this.setState({favoritecolor: "yellow"})
}, 1000)
}
componentDidUpdate() {
document .getElementById("mydiv").innerHTML =
"The updated favorite is " + this.state .favoritecolor ;
}
render() {
return (
<div> <h1>My Favorite Color is {this.state .favoritecolor }</h1> <div id="mydiv"></div> </div>
);
} }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Header />);
|
Unmounting
The next phase in the lifecycle occurs when a component is removed from the DOM, known as unmounting in React. React provides a single built-in method that is called during this process:
componentWillUnmount
The componentWillUnmount method is invoked just before the component is removed from the DOM.
Example:
Press the button to remove the header.
class Container extends React.Component {
constructor(props) {
super(props );
this.state = {show: true};
}
delHeader = () => {
this.setState({show: false});
}
render() {
let myheader ;
if (this.state .show ) {
myheader = <Child />;
};
return (
<div> {myheader } <button type="button" onClick={this.delHeader}>Delete Header</button> </div>
);
} }
class Child extends React.Component {
componentWillUnmount() {
alert("The component named Header is about to be unmounted.");
}
render() {
return (
<h1>Hello World!</h1>
);
} }
const root = ReactDOM .createRoot(document .getElementById('root'));
root .render(<Container />);
|