React componentWillUnmount() Method
The componentWillUnmount() method has the following format:
componentWillUnmount()
The componentWillUnmount() method is called directly before the component is unmounted and destroyed.
setState() should not be called in the componentWillUnmount() method, because the component will never re-render. Once a component instance is unmounted, it will never be mounted again.
In the following example, the componentWillUnmount() method is called when the component is about to be removed from the DOM:
Example
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 the heading component
button
div
)
;
}
}
class
Child
extends
React
.
Component
{
componentWillUnmount
(
)
{
alert
(
"
The heading component is about to unmount.
"
)
;
}
render
(
)
{
return
(
<
h1
Hello
Runoob!
h1
)
;
}
}
Try it »
React Component Lifecycle