Wednesday, August 15, 2018

React Component Lifecycle - getSnapshotBeforeUpdate

The getSnapshotBeforeUpdate life-cycle method is invoked before the DOM is updated. We can use this method to capture any settings / position information from the DOM before it gets updated. We can pass value from this method to the componentDidUpdate life-cycle method as a third parameter. Any value returned from this method will automatically be passed to the componentDidUpdate method.

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Perform any DOM settings / position calculation here
    return ;
  }

  componentDidUpdate(prevProps, prevState, ) {
  }

This life-cycle method is not very frequently used, as we said earlier it can be used to get DOM position / settings before DOM update and perform any DOM related activities. For eg this method can be used to calculate scroll position of large lists based on items added / removed from the list. Calculated position information can be passed to componentDidUpdate as the 3rd parameter.

Another example use-case for this method is, if we want to refresh the component but preserver the scroll position of the component then we can use this method to capture the scroll position before DOM update and re-apply the scroll position after refreshing the DOM.

Below is the syntax for getSnapshotBeforeUpdate 

  getSnapshotBeforeUpdate(prevProps, prevState) {
    // Perform DOM calculations here.
    return myProp;
  }

  componentDidUpdate(prevProps, prevState, snapshot) {
    // Adjust UI positions based on value (snapshot) from getSnapshotBeforeUpdate
  }

Search Flipkart Products:
Flipkart.com

No comments: