Now that we've seen a bit of how state works at at a high level, let's dig into the component's lifecycle methods. Each component goes through a series of stages going from instantiation to being rendered.
So far, as we've seen, when we create a component, we invoked the constructor, and then invoked the render. That was it. There are, however, more methods that we can overload and put to use if we so please!
Mounting
As in the name, these below methods are run once when we mount the component onto the DOM. They are run in the order they appear below:
constructor():
this.props
gets set. this.state = { someStateVar: 0 }
static getDerivedStateFromProps():
render():
REQUIRED! The only component that must be there.
Returns:
return someBoolean && <ChildElement />
componentDidMount():
Note: There does exist a componentWillMount(), however, that method has been deprecated and should be avoided!
Updating
These methods get run when the state or props change. When the component is re-rendered, the following methods are called in the following order:
static getDerivedStateFromProps():
shouldComponentUpdate(nextProps, nextState):
this.props
and this.state
with nextProps
and nextState
to determine if rendering is necessary. render()
getSnapshotBeforeUpdate(prevProps, prevState):
componentDidUpdate()
to the snapshot parametercomponentDidUpdate(prevProps, prevState, snapshot)
Note: there are two updating methods that are considered depracated: componentWillUpdate() and componentWillReceiveProps().
Unmounting:
When a component is no longer being used, it unmounts. When that occurs, the following method is called:
componentWillUnmount():
Error Handling:
When dealing with errors (and there are always errors) during rendering, lifecycle methods, or in any child constructors, the following methods are called:
static getDerivedStateFromError(error)
componentDidCatch