React shouldComponentUpdate() Method
The shouldComponentUpdate() method has the following format:
shouldComponentUpdate(nextProps, nextState)
The shouldComponentUpdate() method returns a boolean value specifying whether React should continue rendering. The default value is true, meaning state the component will re-render on every change.
The return value of shouldComponentUpdate() is used to determine whether a React component's output is affected by changes to the current state or props. When props or state change, shouldComponentUpdate() is called before rendering is performed.
The following example demonstrates what happens when the shouldComponentUpdate() method returns false (clicking the button cannot modify it):
Example
class
Header
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
favoritesite
:
"
runoob
"
}
;
}
shouldComponentUpdate
(
)
{
return
false
;
}
changeSite
=
(
)
=>
{
this
.
setState
(
{
favoritesite
:
"
"
}
)
;
}
render
(
)
{
return
(
<
div
<
h1My favorite website is
{
this
.
state
.
favoritesite
}
h1
< button type = " button " onClick = { this.
changeSite
}
Modify
button
div
)
;
}
}
Try it »
The following example demonstrates what happens when the shouldComponentUpdate() method returns true (clicking the button can modify it):
Example
class
Header
extends
React
.
Component
{
constructor
(
props
)
{
super
(
props
)
;
this
.
state
=
{
favoritesite
:
"
runoob
"
}
;
}
shouldComponentUpdate
(
)
{
return
true
;
}
changeSite
=
(
)
=>
{
this
.
setState
(
{
favoritesite
:
"
"
}
)
;
}
render
(
)
{
return
(
< div < h1My favorite website is
{
this
.
state
.
favoritesite
}
h1
< button type = " button " onClick = { this.
changeSite
}
Modify
button
div
)
;
}
}
Try it »
React Component Lifecycle