Use of state with props in React
Fri Jul 22 2022 06:34:38 GMT+0000 (Coordinated Universal Time)
Saved by
@Harsh_S
#javascript
#react
import React from "react";
class Clock extends React.Component {
constructor(props) { //Constructor is called when root is rendered
super(props);
this.state = { date: new Date() }; //intializes this.state with current time
}
componentDidMount() { //React lifecycle method, is been called when clock output is inserted in the DOM
this.timerID = setInterval(
() => this.tick(),
1000
) //Here class component asks the browser to set up a timer to call the tick() method once a second
}
tick(){
this.setState({ //calling setState method with an object containing the current time
date: new Date()
}); //setState method updates the current time
}
componentWillUnmount() { // Incase if clock component is ever removed from the DOM , react call this lifecycle method so the timer is stopped.
clearInterval(this.timerID)
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>It is {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
export default Clock;
content_copyCOPY
https://reactjs.org/docs/state-and-lifecycle.html
Comments