Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

React getDerivedStateFromProps() Method

React getDerivedStateFromProps() Method

React Component Lifecycle React Component Lifecycle

The getDerivedStateFromProps() method has the following format:

static getDerivedStateFromProps(props, state)

getDerivedStateFromProps is called before the render method, that is, before DOM elements are rendered, and it is called both on initial mount and on subsequent updates.

The value of state depends on props at all times.

getDerivedStateFromProps exists for only one purpose: to let the component update state when props change.

This method returns an object to update state; if it returns null, nothing is updated.

The following example favoritesite has an initial value of runoob, but the getDerivedStateFromProps() method, through thefavsite prop, updates the favoritesite value of:

Example

class

Header

extends

React

.

Component

{

constructor

(

props

)

{

super

(

props

)

;

this

.

state

=

{

favoritesite

:

"

runoob

"

}

;

}

static

getDerivedStateFromProps

(

props

,

state

)

{

return

{

favoritesite

:

props

.

favsite

}

;

}

render

(

)

{

return

(

<

h1

My favorite website is

{

this

.

state

.

favoritesite

}

h1

)

;

}

}

Try it »

Example

class

Header

extends

React

.

Component

{

constructor

(

props

)

{

super

(

props

)

;

this

.

state

=

{

favoritesite

:

"

runoob

"

}

;

}

shouldComponentUpdate

(

)

{

return

true

;

//

Modify this to allow the component to update

}

changeSite

=

(

)

=>

{

this

.

setState

(

{

favoritesite

:

"

google

"

}

)

;

}

render

(

)

{

return

(

<

div

<

h1

My favorite website is

{

this

.

state

.

favoritesite

}

h1

<button type="button" onClick={this>

.

changeSite

}

Modify

button

div

)

;

}

}

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<

Header

/>

)

;

Try it »

React Component Lifecycle React Component Lifecycle