ReactJS | Implementing State & Lifecycle

22 Jan, 2021
We have seen so far what a React web-app is, the states and lifecycle of a React component. We also created a basic clock using a function to re-render the page at each second which if you think can be achieved with or without React. React doesn’t recommend using multiple renders instead it uses a stateful approach where the page is re-rendered once a state is altered. Our aim for this article will be to take up the code we had written in the previous article, and create a stateful solution that will help us achieve the same result. To start let us recall what we had developed in the previous article,
Open your react project directory and edit the Index.js file from src folder:
src index.js: 
javascript
import React from 'react';import ReactDOM from 'react-dom'; function showTime(){const myElement = (                   <div>                        <h1>Welcome to GeeksforGeeks!</h1>                        <h2>{new Date().toLocaleTimeString()}</h2>                   </div>                  );  ReactDOM.render(      myElement,      document.getElementById("root"));                   }  setInterval(showTime, 1000)
Now what is the component in the above example ? Actually, if you pay attention there is no component whatsoever. We are assigning a nested JSX element named “myElement” to contain the latest time and rendering the same every second, which is one of the worst ways to implement using React. Now we will start to implement it using the state and lifecycle methods which will require a classful component, let us start by creating one beforehand. 
Open your react project directory and edit the Index.js file from src folder:
src index.js: 
javascript
import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component {}
Now that we have defined the class to be “Clock” we must think of the process first. “Props” is the set of attributes that rarely change while “State” is the set of observable attributes that are supposed to change over time. Now if we think about our own situation, our clock has exactly two parts one is the title that says “Welcome to GeeksforGeeks!” this should be implemented using props as it will not be changing throughout the lifetime; the other part is the time itself that should be changed at each second. Let us just use the constructor and render method to first create the backbone method to show the title and time without updating it at regular intervals.  
javascript
import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component {    constructor(props)    {        super(props);        this.state = { time : new Date() };    }     render()    {        return (            <div><h1>Welcome to { this.props.title } !</h1>        <h2>{this.state.time}</h2></div>    );  }} ReactDOM.render(  <Clock title="GeeksforGeeks" />,            document.getElementById('root'));
Now that we have created our own component Clock and have rendered what we require, we only need to figure out a way of updating the time each second. Now it is clear that we have to set an interval to update the state at each second and this should be done as soon as the clock component is mounted. Thus, we have to use a lifecycle function componentDidMount() where we will set an interval to update the state, and to make the app efficient we will use componentWillUnmount() method to clear the interval. Let us see the following implementation. 
Open your react project directory and edit the Index.js file from src folder:
src index.js: 
javascript
import React from 'react';import ReactDOM from 'react-dom'; class Clock extends React.Component {    constructor(props)    {        super(props);        this.state = { time : new Date() };    }     // As soon as the Clock is mounted.    // Start the interval "timer".    // Call tick() every second.    componentDidMount()    {        this.timer = setInterval(            () => this.tick(),            1000);    }     // Before unmounting the Clock,    // Clear the interval "Timer"    // This step is a memory efficient step.    componentWillUnmount()    {        clearInterval(this.timer);    }     // This function updates the state,    // invokes re-render at each second.    tick()    {        this.setState({            time : new Date()        });    }     render()    {        return (            <div><h1>Welcome to { this.props.title } !</h1>        <h2>{this.state.time.toLocaleTimeString()}</h2></div>    );  }} ReactDOM.render(  <Clock title="GeeksforGeeks" />,            document.getElementById('root'));
Congratulations! You just created a React web app using States, Props, and some lifecycle methods. You might be asking is that all? No, it isn’t even a nibble of the whole platter stay tuned for the upcoming articles where we dive deeper into React and create some more projects on the go. 
shubhamyadav4
react-js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Remove elements from a JavaScript Array
REST API (Introduction)
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to create footer to stay at the bottom of a Web page?