React componentDidMount() Method
The componentDidMount() method has the following format:
componentDidMount()
The componentDidMount() method is called immediately after the component is mounted (inserted into the DOM tree).
Initialization that depends on DOM nodes should be placed in the componentDidMount() method.
The following example first outputs runoob, then uses the componentDidMount() method to set the output after the component is mounted google:
Example
class
Header
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
favoritesite
:
"
runoob
"
}
;
}
componentDidMount
(
)
{
setTimeout
(
(
)
=>
{
this
.
setState
(
{
favoritesite
:
"
"
}
)
}
,
1000
)
}
render
(
)
{
return
(
<
h1
My favorite website is
{
this
.
state
.
favoritesite
}
h1
)
;
}
}
Try it »
React Component Lifecycle