Every component in React goes through a lifecycle of events. I like to think of them as going through a cycle of birth, growth, and death.
Mounting – Birth of your component
Update – Growth of your component
Unmount – Death of your component
Mounting
1-constructor(props)
2-getDerivedStateFromProp(props, state)
3-render
4-componentDidMount
Updating
1-getDerivedStateFromProp
2-shouldComponentUpdate
3-render
4-getSnapshotBeforeUpdate
5-componentDidUpdate
Unmounting
1-componentWillUnmount
class EmailInput extends Component { state = { email: this.props.defaultEmail, prevPropsUserID: this.props.userID }; static getDerivedStateFromProps(props, state) { // Any time the current user changes, // Reset any parts of state that are tied to that user. // In this simple example, that's just the email. if (props.userID !== state.prevPropsUserID) { return { prevPropsUserID: props.userID, email: props.defaultEmail }; } return null; } }
Example 2: getDerivedStateFromProps
class List extends React.Component { static getDerivedStateFromProps(props, state) { if (props.selected !== state.selected) { return { selected: props.selected, }; } // Return null if the state hasn't changed return null; } // ... }
