React › Class Components & Legacy Lifecycle Methods
What is componentDidUpdate used for, and what mistake should you watch out for when using it?
AdvancedAnswer
componentDidUpdate runs every time a component re renders after its props or state change, which makes it useful for reacting to a specific value changing, such as fetching new data when an id prop updates. A common mistake is calling setState inside it without a condition, which can trigger the component to update over and over in an endless loop.
componentDidUpdate(prevProps) {
if (prevProps.userId !== this.props.userId) {
this.fetchUser(this.props.userId); // only runs when userId actually changes
}
}Real-world example A profile page component checks whether the userId prop changed before fetching new data inside componentDidUpdate, avoiding an endless loop of unnecessary requests every time the component updates for any reason.