YouTip LogoYouTip

React Ref Getderivedstatefromprops

# React getDerivedStateFromProps() Method [![Image 3: React Component Lifecycle](#) React Component Lifecycle](#) The getDerivedStateFromProps() method format is as follows: static getDerivedStateFromProps(props, state) getDerivedStateFromProps is called before calling the render method, that is, before rendering DOM elements, and it will be called during initial mounting and subsequent updates. The value of state depends on props at all times. The sole purpose of getDerivedStateFromProps is to let the component update state when props change. This method returns an object to update state, or returns null to update nothing. In the following example, the initial value of **favoritesite** is ****, but the getDerivedStateFromProps() method updates the value of **favoritesite** through the **favsite** property: ## Example class Header extends React.Component{constructor(props){super(props); this.state = {favoritesite: ""}; }static getDerivedStateFromProps(props, state){return{favoritesite: props.favsite}; }render(){return(

My favorite site is {this.state.favoritesite}

); }} [Try it Β»](#) ## Example class Header extends React.Component{constructor(props){super(props); this.state = {favoritesite: ""}; }shouldComponentUpdate(){return true; // Modify here to allow component update}changeSite = () =>{this.setState({favoritesite: "google"}); }render(){return(

My favorite site is {this.state.favoritesite}

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