Class components can define functions that will execute at certain points during the component’s lifecycle. Using them can give a finer level of control over components. Here’s an overview of the available lifecycle functions in React.
The following examples are very bad React and are for demonstrative purposes only.
componentWillMount
is called before the component is rendered for the first time. You can use this to call setState
before the initial render.
class Scorecard extends Component {
componentWillMount() {
this.setState({score: 0});
}
render() {
const {playerName} = this.props;
// `this.state` defaults to null, but since it'll be set in
// `componentWillMount`, it can safely be destructured.
const {score} = this.state;
const message = `Current Score: ${score}`;
return (
<div>
<h1>{playerName}</h1>
<div>{message}</div>
</div>
);
}
}
Calling setState
will usually trigger a re-render, but calling it in componentWillMount
won’t (since it hasn’t rendered in the first place).
componentDidMount
is called after the component is rendered for the first time. This can be used to start an async operation as soon as the component shows up.
class Scorecard extends Component {
// Other functions omitted for brevity.
componentDidMount() {
// You'd probably want to send an AJAX call or something,
// but let's say they get 1000 points after the first second.
setTimeout(() => this.setState({score: 1000}), 1000);
}
}
componentDidMount
won’t be called in server rendering.
componentWillReceiveProps
is called when the component receives new props, but before it renders. You can call setState
here without causing another re-render, since there’s already one pending.
class Scorecard extends Component {
// Other functions omitted for brevity.
componentWillReceiveProps(nextProps) {
// `nextProps` is the new props, while `this.props` are the old ones.
const {playerName} = this.props;
// It is entirely possible that the new `playerName` is the same as the old one.
if (nextProps.playerName !== playerName) {
// Changing your name resets the score to zero.
this.setState({score: 0});
}
}
}
shouldComponentUpdate
is called after props or state are changed (and after componentWillReceiveProps
), but before it renders. It’s unique among lifecycle functions in that it is expected to return a boolean value. If false, render
will not be called. This can be very useful for skipping unnecessary renders and save some CPU.
class Scorecard extends Component {
// Other functions omitted for brevity.
shouldComponentUpdate(nextProps, nextState) {
// Same as `componentWillReceiveProps`, `nextProps` is the
// new props and `this.props` is the old.
const {playerName} = this.props;
// Ditto for `nextState` and `this.state`.
const {score} = this.state;
// Only `playerName` and `score` affect the display.
// If something else changes, re-rendering would be a waste.
return !(nextProps.playerName === playerName && nextState.score === score);
}
}
componentWillUpdate
is called right before the component renders and right after shouldComponentUpdate
. It can’t call setState
.
class Scorecard extends Component {
// Other functions omitted for brevity.
componentWillUpdate(nextProps, nextState) {
const {playerName} = this.props;
// If `playerName` changes, log a message.
if (nextProps.playerName !== playerName) {
// Note that even though `componentWillReceiveProps` called `setState`, `this.state` is still the original value.
const {score} = this.state;
console.log(`${playerName} is now ${nextProps.playerName}. His score of ${score} is forfeit.`);
}
}
}
componentDidUpdate
is called after render
is finished. As with the other update functions, it’ll have both the new and old versions of props and state, but with the previous versions as the parameters, instead.
class Scorecard extends Component {
// Other functions omitted for brevity.
componentDidUpdate(prevProps, prevState) {
const {playerName} = this.props;
// You guessed it, `prevProps` are the props as they used to be and `this.props` are what they are now.
// Ditto for `prevState` and `this.state`.
if (prevProps.playerName !== playerName) {
const {score} = prevState;
console.log(`${playerName} used to be ${prevProps.playerName}. His former score was ${score}.`);
}
}
}
Lastly, componentWillUnmount
is called before the component is removed. Use it to say your goodbyes.
class Scorecard extends Component {
// Other functions omitted for brevity.
componentWillUnmount() {
console.log('Sayonara!');
}
}
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Good explanation. Some outdated lifecycle events can be mentioned above and a way to migrate them would be helpful.
This is useful. Thanks