These are methods that allow us to execute certain functionality during the Component´s life-cycle (this is for Class-based Components
. We will see as well hooks
which are the "equivalent" for Functional Components
).
Order of execution:
constructor(props)
> InitializationgetDerivedStateFromProps(props, state)
> To update state based on changes on propsshouldComponentUpdate(nextProps, nextState)
> We can stop or prevent unnecessary re-renders improving performance.render()
> Logic and return. It will render the particular component and its child.getSnapshotBeforeUpdate(prevProps, prevState)
> Returns a snapshot (object).componenDidMount()
> Here's where we cause or produce side-effects like fetching data (HTTP request)componentDidUpdate(prevProps, prevState, snapshot)
> Here's where we cause or produce side-effects like fetching data (HTTP request)
Deprecated life-cycles
componentWillMount()
: before the Component is inserted into the DOMcomponentWillReceiveProps()
: whenever the component is going to receive NEW propscomponentWillUnmount()
: before the Component is removed from the DOM
App > constructor()
App > getDerivedStateFromProps() {}
App > render()
Child > render()
App > componentDidMount()
And, if you click in the button (which updates the state property name in App Component
and passes it to Child as props
):
App > getDerivedStateFromProps() {}
App > render()
Child > shouldComponentUpdate()
Child > render()
Child > getSnapshotBeforeUpdate()
Child > componentDidUpdate()
{friend: "Peter"}
You will also see the following warnings that will prevent the execution of "the will life-cycles"
Warning: Unsafe legacy lifecycles will not be called for components using new component APIs.
App uses getDerivedStateFromProps() but also contains the following legacy lifecycles:
componentWillMount
Warning: Unsafe legacy lifecycles will not be called for components using new component APIs.
Child uses getSnapshotBeforeUpdate() but also contains the following legacy lifecycles:
componentWillReceiveProps
componentWillUpdate