Remember componentDidMount and componentDidUpdate?

If you have worked with React before, you have probably used the componentDidMount and componentDidUpdate life cycle methods. For example, we can set the document title to a given prop as follows, using a React class component. In the following code section, the life cycle method is highlighted in bold:

import React from 'react'

class App extends React.Component {
componentDidMount () {
const { title } = this.props
document.title = title
}

render () {
return (
<div>Test App</div>
)
}
}

This works fine. However, when the title prop updates, the change does not get reflected in the title of our web page. To solve this problem, we need to define the componentDidUpdate life cycle method (new code in bold), as follows:

import React from 'react'

class App extends React.Component {
componentDidMount () {
const { title } = this.props
document.title = title
}

componentDidUpdate (prevProps) {
const { title } = this.props
if (title !== prevProps.title) {

document.title = title
}

}

render () {
return (
<div>Test App</div>
)
}
}

You might have noticed that we are writing almost the same code twice; therefore, we could create a new method to deal with updates to title, and then call it from both life cycle methods. In the following code section, the updated code is highlighted in bold:

import React from 'react'

class App extends React.Component {
updateTitle () {
const { title } = this.props
document.title = title
}

componentDidMount () {
this.updateTitle()
}

componentDidUpdate (prevProps) {
if (this.props.title !== prevProps.title) {
this.updateTitle()
}

}

render () {
return (
<div>Test App</div>
)
}
}

However, we still need to call this.updateTitle() twice. When we update the code later on, and, for example, pass an argument to this.updateTitle(), we always need to remember to pass it in both calls to the method. If we forget to update one of the life cycle methods, we might introduce bugs. Furthermore, we need to add an if condition to componentDidUpdate, in order to avoid calling this.updateTitle() when the title prop did not change.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.10.246