React.js Component Lifecycle - Unmounting
- ComponentWillUnmount is the only method that executes in unmount phase.
- Component enters into this phase when there is no matching in element tree for this component.
- Just before the component gets removed from actual DOM, this method gets called.
- Along with removal of this component from DOM tree, all children of this component also gets removed automatically.
- Once component is removed from the DOM, it gets available for the garbage collection in React.
- Cleanup activities can be done in this method. E.g. clear localstorage variables used in app, clear session, clean up charts, cleanup timers, cancel pending api requests etc.
this.resetSession(); //example method to clean data
- Cleanup activities helps in improving performances, memory leakages and maintain security.
- In latest release 16.4 +, three methods are marked as deprecated and renamed as well. These methods will be removed in next major release of React.js
- componentWillReceiveProps changed to UNSAFE_componentWillReceiveProps . This method is implemented securely and statically with name getDerivedStateFromProps
- componentWillMount changed to UNSAFE_componentWillMount. Code from this method should be moved to componentDidMount or constructor as per logic.
- componentWillUpdate changed to UNSAFE_componentWillUpdate. Secure implementation is getSnapshotBeforeUpdate. If there is any value returned from this method then it will used as an argument in the next method i.e. componentDidUpdate.
- If user closes browser then the componentWiIlUnmount will not complete.
- componentWillUnmount does not have any argument. setState shold not be called from this method. This is a one-time call for the component. Purpose of this method is to destroy the side effects created by the component.
- Once component is unmounted, we can’t use it again. Every time a new component gets created.
- Also if there is no difference in virtual dom and actual dom, react can stop the update phase as well.
Published on 04-Sep-2019 11:52:05