React have many methods or “hooks” that are called during the lifecycle of an component, which allows us to update the UI and application state. Here we are going to discuss more about it and will see when to use which lifecycle method.This is applicable from the React v16.4.
Here goes the lifecycle cheat diagram
Lifecycle can be divided into three phases - Mounting,Updating and Unmounting.
During Mounting, the following methods are called in order —
constructor → getDerivedStateFromProps →render →componentDidMount.
During Updating, the following methods are called in order —
getDerivedStateFromProps →shouldComponentUpdate, →render, →getSnapshotBeforeUpdate →componentDidUpdate
During Unmounting, only componentWillUnmount is called.
For error handling, in a lifecycle method or in the constructor of any child component, we can use componentDidCatch.
Note : In the list above, commonly used lifecycle methods are marked as bold. The rest of them (Bold+italics) exist for relatively rare use cases.
Mounting Phase:
constructor:
The constructor for a React component is called before it is mounted. Constructor is the only place where you should assign this.state
directly. In all other methods, you need to use this.setState()
instead. Avoid introducing any side-effects or subscriptions in the constructor.
Syntax : constructor(props)
Use : set initial state and Binding event handler methods.
getDerivedStateFromProps:
getDerivedStateFromProps
is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
Syntax : static getDerivedStateFromProps(props, state)
Use : It enables a component to update its internal state as the result of changes in props.
Read more about this here
render:
The render()
method is the only required method in a class component. The render()
function should be pure, meaning that it does not modify component state, it returns the same result each time it’s invoked, and it does not directly interact with the browser.
Syntax: render()
Use : When called, it should examine this.props
and this.state
and return one of the following types: React elements, Arrays and fragments, Portals, String and numbers, Booleans or null.
componentDidMount:
componentDidMount()
is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. You may call setState()
immediately in componentDidMount()
. It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render()
will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues. In most cases, you should be able to assign the initial state in the constructor()
instead. It can, however, be necessary for some cases.
Syntax : componentDidMount()
Use : load data from a remote endpoint
Updating:
shouldComponentUpdate:
The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior. shouldComponentUpdate()
is invoked before rendering when new props or state are being received. Defaults to true
. This method is not called for the initial render or when forceUpdate()
is used.
Consider using the built-in PureComponent
instead of writing shouldComponentUpdate()
by hand.React.PureComponent
is similar to React.Component
. The difference between them is that React.Component
doesn’t implement shouldComponentUpdate()
, but React.PureComponent
implements it with a shallow prop and state comparison.
If you are confident you want to write it by hand, you may compare this.props
with nextProps
and this.state
with nextState
and return false
to tell React the update can be skipped. Note that returning false
does not prevent child components from re-rendering when their state changes.
Syntax : shouldComponentUpdate(nextProps, nextState)
Use : This method only exists as a performance optimization.
getSnapshotBeforeUpdate:
getSnapshotBeforeUpdate()
is invoked right before the most recently rendered output is committed to the DOM. Any value returned by this lifecycle will be passed as a parameter to componentDidUpdate()
.
Syntax : getSnapshotBeforeUpdate(prevProps, prevState)
Use : It enables your component to capture some information from the DOM (e.g. scroll position) before it is potentially changed.
componentDidUpdate:
componentDidUpdate()
is invoked immediately after updating occurs. This method is not called for the initial render. You may call setState()
immediately in componentDidUpdate()
but note that it must be wrapped in a condition , or you’ll cause an infinite loop. It would also cause an extra re-rendering which, while not visible to the user, can affect the component performance. If your component implements the getSnapshotBeforeUpdate()
lifecycle (which is rare), the value it returns will be passed as a third “snapshot” parameter to componentDidUpdate()
. Otherwise this parameter will be undefined.
Syntax : componentDidUpdate(prevProps, prevState, snapshot)
Use : Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous prop
Unmounting:
componentWillUnmount:
componentWillUnmount()
is invoked immediately before a component is unmounted and destroyed. You should not call setState()
in componentWillUnmount()
because the component will never be re-rendered. Once a component instance is unmounted, it will never be mounted again.
Syntax :componentWillUnmount()
Use : Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any subscriptions that were created in componentDidMount()
.
Error Handling
componentDidCatch:
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them. A class component becomes an error boundary if it defines this lifecycle method. Calling setState()
in it lets you capture an unhandled JavaScript error in the below tree and display a fallback UI. Only use error boundaries for recovering from unexpected exceptions; don’t try to use them for control flow.
syntax : componentDidCatch(error, info)
Use : Display fallback UI in case of error.
Happy Learning!