DEV Community

KeeyboardKeda
KeeyboardKeda

Posted on

THE STATE OF my REACT...ion

I'm getting further along in react. I'm on the section about state and lifecycles. The example used in the reading is to create a clock that tells time (of course) and updates itself in real time using state and lifecycle.

This is the code:

class Clock extends React.Component {
constructor(props) {
super(props);
this.state = {date: new Date()};
}

componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}

componentWillUnmount() {
clearInterval(this.timerID);
}

tick() {
this.setState({
date: new Date()
});
}

render() {
return (


Hello, world!


It is {this.state.date.toLocaleTimeString()}.



);
}
}

ReactDOM.render(
,
document.getElementById('root')
);

From my understanding:

  1. < Clock /> being in React.render()is how you call everything in the clock component.

2.State is private and is controlled by the component. It is like props but replaces it in this example for the date.

3.state is taking and holding in date.toLocaleTimeString() as a value for the Clock component.

Later on in the example a constructor is added and this.state = {date: new Date ()} is declared inside of it.

In my head:

  • this.state has the value of date: new Date which is used to return the current date. Example, date: March 26 2021 , if i click on the page the next day...date: new Date() will produce March 27 2021.

Lifecyle Methods:

Lifecycles are special methods like mount(componentDidMount())and unmount (componentWillUnmount()) in react.

I won't make this too deep but I'm trying to find a way to understand this in a way that sticks. I'm trying to see why certain things are necessary.

Until next time!

Discussion (0)