React JS - componentWillUnmount Life Cycle Method



componentWillUnmount() method is called in Unmounting phase, when a component is removed from the DOM.

During toggle when he hide an element, componentWillUnmount() method is called.

componentWillUnmount() method works only when we have two components, one parent component and another child component.

In the below example, we are using Show/Hide effect using state. If state is true, the child component will be shown otherwise componentWillUnmount() method is called and component gets hidden/removed from DOM.





















Output :









Github :

https://github.com/eramitsinha/React-Dummy/blob/main/src/ComponentWillUnmount1.js

https://github.com/eramitsinha/React-Dummy/blob/main/src/ComponentWillUnmount2.js

Interview Question

Question) If parent component is Functional component and child component is Class component, then will componentWillUnmount() method work?

YES, component having componentWillUnmount() method should be class component.

Comments