This is the fourth article in ReactJS – Zero to Hero Series. I will recommend reading the first three articles (link given below), before going through this article.
In this article, we will see what State and Lifecycle are in React.
- React support a feature state that is similar to props, but it is private and fully controlled by the component.
- This feature is typically available to components defined as classes since they can support a local state which is completely controlled by the component.
So far, we have only learned one way to update the UI. We call ReactDOM.render() to change the rendered output.
Now, we will create a Clock component and we will learn how to make the Clock component truly reusable and encapsulated. It will set up its own timer and update itself every second.
We can write a Clock component which will be called from the function tick(), as shown below,
- function Clock(props) {
- return (
- <div>
- <h1>Hello, world!</h1>
- <h2>It is {props.date.toLocaleTimeString()}.</h2>
- </div>
- );
- }
- function tick() {
- ReactDOM.render(
- <Clock date={new Date()} />,
- document.getElementById('root')
- );
- }
- setInterval(tick, 1000);
However, the above code misses a very crucial part. In the above code, the setting up of Timer and updating the UI should be the implementation detail of the Clock, however, the implementation is getting executed from the tick() function. Ideally, we want to write this once and have the Clock update itself, as shown below:-
- ReactDOM.render(
- <Clock />,
- document.getElementById('root')
- );
To implement this, we need to add "state" to the Clock component.
How to convert a function to a Class
We can convert a functional component like Clock to a class in five steps,
- Create an ES6 class with the same name that extends React.Component.
- Add a single empty method to it called render().
- Move the body of the function into the render() method.
- Replace props with this.props in the render() body.
- Delete the remaining empty function declaration.

Join the conversation! Your thoughts help the community grow.