×

React Js

The World's best Software Development Study Portal

React JS Lifecycle

React js lifecylce is has divided into 3 phase 1. Mounting 2. Updating 3. Unmounting

React js Mounting has four methods -

constructor()

getDerivedStateFromProps()

render()

componentDidMount()

1. constructor() - When every time component is initiated then constructor() is called. If we are making the new component then every time automatically constructor() is called. Its also called with props. With constructor we should always called super(props). 2. getDerivedStateFromProps() - getDerivedStateFromProps called before the render method. class Header extends React.Component { constructor(props) { super(props); this.state = {color: "red"}; } static getDerivedStateFromProps(props, state) { return {favoritecolor: props.color }; } render() { return ( <h1>My Favorite Color is {this.state.color}</h1> ); } } export default Header; 3. render() - In reactjs render method inform react what to display and return method what to print. 4. componentDidMount() - In reactjs componentDidMount() is called after the component is complete or its redered. class App extends React.Component { constructor(props) { super(props); this.state = {Name: "Welcome to ITC"}; } componentDidMount() { setTimeout(() => { this.setState({Name: "You are in ITC website"}) }, 1000) } render() { return ( <h1>My Favorite Color is {this.state.Name}</h1> ); } } export default App;

React js Updating has four methods -

Component is updated whenever there is change in state or props

constructor()

getDerivedStateFromProps()

render()

componentDidMount()

getSnapshotBeforeUpdate()

1. constructor() - When every time component is initiated then constructor() is called. If we are making the new component then every time automatically constructor() is called. Its also called with props. With constructor we should always called super(props). 2. getDerivedStateFromProps() - getDerivedStateFromProps called before the render method. class Header extends React.Component { constructor(props) { super(props); this.state = {favoritecolor: "red"}; } static getDerivedStateFromProps(props, state) { return {favoritecolor: props.favcol }; } render() { return ( <h1>My Favorite Color is {this.state.favoritecolor}</h1> ); } } export default Header; 3. render() - In reactjs render method inform react what to display and return method what to print. 4. componentDidMount() - In reactjs componentDidMount() is called after the component is complete or its redered. class App extends React.Component { constructor(props) { super(props); this.state = {Name: "Welcome to ITC"}; } componentDidMount() { setTimeout(() => { this.setState({Name: "You are in ITC website"}) }, 1000) } render() { return ( <h1>My Favorite Color is {this.state.Name}</h1> ); } } export default App;