React Lifecycle Methods
Why Lifecycle Methods
we can use the component lifecycle methods of React that allows us execute actions at particular times.
In React every component will have following phases in its Lifecycle:
- Mounting phase - when the component is mounted to DOM tree
- Updating phase - when component is being updated with new state, new props are being received
- Unmounting phase - destroying component from DOM tree
- Error Handling - Handling errors within React Component
- Every phase in the lifecycle of a component has few methods which will be invoked during that phase of a component's lifecycle. We can override these methods to provide the desired functionality.
These methods can be used in the following cases:
For making an Ajax call, to set timer and to integrate with other frameworks
To avoid unnecessary re-rendering of a component
To update the component, based on the props changes
For clearing the values when component is unmounted
Mounting Phase
At mounting phase of a component, following methods which will be invoked:
constructor()
static getDerivedStateFromProps()
render()
componentDidMount()
constructor(): Constructors are used only for the below 2 purposes which we have already seen in the state demo:
Initializing state of a component
For binding event handler methods to an instance
static getDerivedStateFromProps(): getDerivedStateFromProps() is invoked right before the render method. This method is called both in mounting and updating phase.
getDerivedStateFromProps() is a static method. Since it is a static method, we cannot access 'this' keyword within this method. Hence we cannot call setState method.
This method returns an object which will be the updated state and return null if there is no state update.
render(): Every React component must have render() method. render() method should be a pure function which returns the same result every time it is called which means, it doesn't modify any component's state.
componentDidMount():
Invoked immediately after the component is mounted to DOM tree
Now will have access to all the DOM nodes hence any initialization which requires DOM nodes should be done here
Best place for setting timers and handling Ajax request .
Updating Phase
At updating phase of a component, below methods are executed based on props or state being received and updates happens in a component:
static getDerivedStateFromProps()
shouldComponentUpdate()
render()
getSnapshotBeforeUpdate()
componentDidUpdate()
shouldComponentUpdate(nextProps, nextState):
- Executed before rendering when new state or props are being received
- By default it will return true by calling componentDidUpdate() method. If it returns false componentDidUpdate() method will not be invoked .
- In case we want to skip re-rendering, this method could be used by returning false, so this would skip re-rendering.
- This method only exists as a performance optimization .
getSnapshotBeforeUpdate(prevProps, prevState):
- Invoked right before changes are made to the DOM
- It is recommended to return a value from this method which will be passed as a third parameter(as 'snapshot') to the componentDidUpdate()
- Once the updates flushed to the DOM, immediately next lifecycle method will be invoked.
This method is called immediately after the render and before the changes are uodated to the DOM.
This method is the last chance to get the prevState and prevProps values before the component is updated. The method can return values based on the prevState and prevProps values.
One Use case is saving scroll position of screen in a chat window.
componentDidUpdate(prevProps, prevState, snapshot):
- Invoked immediately after the changes are updated.
Unmounting Phase
componentWillUnmount() method will be invoked immediately before a component is unmounted and destroyed.
This method is used at the unmounting process of a component .
This is the place for performing any necessary cleanup. e.g: any subscription which was created in componentDidMount()
A component can be unmounted from DOM using ReactDOM.unmountComponentAtNode()
In a react Time App componentWillUnmount() can be added in the Timer component and updated as follows:
componentWillUnmount(){
console.log('Component WILL UNMOUNT!')
//clean up code
clearInterval(this.interval);
}
Error Handling:
Why Error Handling and How :
Why : To handle the scenarios where an error can be occured. How : In react we use error boundaries because throwing direct error from vanilla JS would not show in which component the Error has occured. Error boundries allows us to StackTrace the component Tree and render a fall back UI when an error is Occurred.
Error handling can be taken care in React using the below methods
static getDerivedStateFromError()
componentDidCatch()
Error boundaries should be defined in order to catch errors occurring within the child components. Whenever a component crashes because of a JavaScript error, the error will be logged and fall back UI is displayed.
Error boundaries are nothing but class components which defines either getDerivedStateFromError or componentDidCatch method.
The ErrorHandler is just a class component which implements the componentDidCatch method. The componentDidCatch method receives the error and info as arguments.
error is the actual error message which tells the reason for the error and info contains stack trace of the error
STEPS : I) Define Error boundaries Component ii) wrap your component inside the error boundry component .
NOTE: we need to wrap each component with it's own error boundary. BCOZ if we wrap two components in a single error boundary then if error occurs in component then both component will fail .