React Component Lifecycle - Unmount Phase
As we have seen the basics of the React Component Lifecycle, lets get into the action!
We have see how mounting & update phase works. Today we will look into the update phase. As discussed earlier, there is 1 major method:
- componentWillUnmount()
componentWillUnmout will be called when component is being removed from the DOM.
Lets look at an example:
class ReactLifecycle extends React.Component {
constructor() {
super();
this.state = {
clickCount: 0,
//use this flag to remove the child
showChild: true,
};
this.incrementHandler = this.incrementHandler.bind(this);
this.resetHandler = this.resetHandler.bind(this);
}
//We will remove child component through this method, pass as props to child
removeChild = () => {
const showChild = !this.state.showChild;
this.setState({ showChild });
};
incrementHandler = (event, name) => {
console.log("clickCount is incremented by One...");
const newClickCount = this.state.clickCount + 1;
this.setState({ clickCount: newClickCount });
};
resetHandler = () => {
console.log("clickCount is reset to Zero..");
const newClickCount = 0;
this.setState({ clickCount: newClickCount });
};
render() {
console.log("Render method of Parent Component is called.");
return (
<>
<h1>Hello, Total clicks are {this.state.clickCount}</h1>
{this.state.showChild ? (
//passing removeChild method to child component via props
<Child removeChild={this.removeChild} />
) : (
<></>
)}
<button className="btn" onClick={(event) => this.incrementHandler()}>
Click Now to increment!
</button>
<button className="btn" onClick={(event) => this.resetHandler()}>
Reset Count!
</button>
</>
);
}
}
class Child extends React.Component {
//this will be called when Child component is being removed
componentWillUnmount() {
console.log("componentWillUnmount method of Child is called.");
}
render({ removeChild } = this.props) {
console.log("Render method of Child Component is called.");
return (
<>
<h2>This is a Child Component...</h2>
{/* This will remove the child component */}
<button className="btn" onClick={(event) => removeChild()}>
Remove Child Component!
</button>
</>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<ReactLifecycle />, rootElement);
Output:
- Before child component is removed:
- Note that we have incremented clickCount and with that change, child component is re-rendered before we removed the child component by clicking on the Remove Child Component button.
- After child component is removed
- Post clicking the Remove Child Component button, notice how componentWillUnmount() method of child is called.
- Also notice that the parent component did not re-render post removal of child component.
- The functionality of parent component was working as expected post removal of child component.
Comments
Post a Comment