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.
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.
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.
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.
componentWillUpdate
is called right before the component renders and right after shouldComponentUpdate
. It can’t call setState
.
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.
Lastly, componentWillUnmount
is called before the component is removed. Use it to say your goodbyes.
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!
This is useful. Thanks
Good explanation. Some outdated lifecycle events can be mentioned above and a way to migrate them would be helpful.