Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active February 26, 2020 16:46
Show Gist options
  • Save ross-u/6d5c2ca9fa75f5815b547baee440f84c to your computer and use it in GitHub Desktop.
Save ross-u/6d5c2ca9fa75f5815b547baee440f84c to your computer and use it in GitHub Desktop.
React Lifecycle methods - II Updating - componentDidUpdate()

React | Lifecycle methods


II - Updating

An update phase can be caused by changes of the props or state.

Update phase is initiated by passing new props, setState() or forceUpdate().


Mounting phase happens just once, where the updating phase happens every time on change of the state or the props.


These methods are called in the following order when a component is updated:

  • render() - Invoked by default each time an update happens (new props, setState or forceUpdate)

  • componentDidUpdate()


componentDidUpdate()

  • componentDidUpdate() is invoked only during the updating phase, immediately after the re-render() is finished.

  • We shouldn’t update the state in componentDidUpdate(). This can cause infinite loop if the proper condition is not set, and it causes an extra re-rendering (affects component performance).

  • componentDidUpdate() gives us access to the props and state from when before the update was made( componentDidUpdate(prevProps, prevState) ).

  • Commonly componentDidUpdate()is used for comparing the previous prevProps and prevStateversus current this.props and this.state to see what exactly changed (if anything) and then react accordingly.

// ...
class App extends React.Component {
// ...
// ...
// CREATE A METHOD TO UPDATE `currentTime` IN THE `state`
updateTime = () => {
const currentTime = new Date().toUTCString();
this.setState({ currentTime });
}
// ...
// ...
render () {
// ...
// ...
<button onClick={this.updateTime}> UPDATE TIME </button> // <-- ADD A BUTTON
{
this.state.showClock
? <Clock currentYear={2020} currentTime={ this.state.currentTime }/>
: null
} {/* ^ ^ ^ PASS NEW PROP ^ ^ ^ */}
// ...
class Clock extends React.Component {
constructor(props) {
// ...
};
componentDidMount() {
// ...
}
componentDidUpdate(prevProps, prevState) {
/* code to run after the update happens via
passing new `props`,
or by calling the `setState` or `forceUpdate` */
console.log('IN "COMPONENT DID UPDATE"');
}
render() {
return (
<div>
<h1>Clock</h1>
<h2>Year</h2>
<p>{this.state.year}</p>
<h2>Current Time</h2> {/* <-- ADD */}
<p>
{
this.props.currentTime
? this.props.currentTime
: 'LOADING'
}
</p>
{/* We are passing currentTime by clicking the button in <App /> component */}
</div>
);
}
}
// Check if new props are passed
componentDidUpdate(prevProps) {
console.log('IN "COMPONENT DID UPDATE"');
// Typical usage - comparing value of the new props:
if (prevProps.currentTime !== this.props.currentTime) {
console.log(' RECEIVED NEW PROPS ! ! !');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment