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

React getSnapshotBeforeUpdate() Method

React getSnapshotBeforeUpdate() Method

React Component Lifecycle React Component Lifecycle

The getSnapshotBeforeUpdate() method has the following format:

getSnapshotBeforeUpdate(prevProps, prevState)

The getSnapshotBeforeUpdate() method is called right before the most recent render output is committed to the DOM nodes.

In the getSnapshotBeforeUpdate() method, we can access the props and state from before the update.

The getSnapshotBeforeUpdate() method needs to be used together with the componentDidUpdate() method, otherwise an error will occur.

The following example uses getSnapshotBeforeUpdate() This method looks at the values in the state object before the update; the example shows the different values before and after the update after a 1-second delay:

Example

class

Header

extends

React

.

Component

{

constructor

(

props

)

{

super

(

props

)

;

this

.

state

=

{

favoritesite

:

"

runoob

"

}

;

}

componentDidMount

(

)

{

setTimeout

(

(

)

=>

{

this

.

setState

(

{

favoritesite

:

"

google

"

}

)

}

,

1000

)

}

getSnapshotBeforeUpdate

(

prevProps

,

prevState

)

{

document

.

getElementById

(

"

div1

"

)

.

innerHTML

=

"

The favorite website before the update is:

"

prevState

.

favoritesite

;

}

componentDidUpdate

(

)

{

document

.

getElementById

(

"

div2

"

)

.

innerHTML

=

"

The favorite website after the update is:

"

this

.

state

.

favoritesite

;

}

render

(

)

{

return

(

<

div

<

h1

My favorite website is

{

this

.

state

.

favoritesite

}

h1

<div id="div1" div>
<div id="div2" div div)>

;

}

}

const

root

=

ReactDOM

.

createRoot

(

document

.

getElementById

(

"

root

"

)

)

;

root

.

render

(

<

Header

/>

)

;

Try it »

React Component Lifecycle React Component Lifecycle