YouTip LogoYouTip

React Ref Getsnapshotbeforeupdate

# React getSnapshotBeforeUpdate() Method [![Image 3: React Component Lifecycle](#) React Component Lifecycle](#) The getSnapshotBeforeUpdate() method has the following format: getSnapshotBeforeUpdate(prevProps, prevState) The getSnapshotBeforeUpdate() method is called before the most recent render output (committed to the DOM nodes). In the getSnapshotBeforeUpdate() method, we can access the props and state before the update. The getSnapshotBeforeUpdate() method needs to be used together with the componentDidUpdate() method, otherwise an error will occur. The following example uses the getSnapshotBeforeUpdate() method to view the value of the state object before the update. The example will display the different values before and after the update after a 1-second delay: ## Example class Header extends React.Component{ constructor(props){ super(props); this.state = {favoritesite: ""}; } componentDidMount(){ setTimeout(() => { this.setState({favoritesite: "google"}) }, 1000) } getSnapshotBeforeUpdate(prevProps, prevState){ document.getElementById("div1").innerHTML = "Before update, favorite website was: " + prevState.favoritesite; } componentDidUpdate(){ document.getElementById("div2").innerHTML = "After update, favorite website is: " + this.state.favoritesite; } render(){ return(

My favorite website is {this.state.favoritesite}

); } } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(
); [Try it yourself Β»](#) [![Image 4: React Component Lifecycle](#) React Component Lifecycle](#)
← React Ref ComponentwillunmountReact Ref Componentdidmount β†’