ReactJS Tutorial

Implementation of State and Lifecycle in ReactJS

How to Implement State in ReactJS?

Using multiple renders is not recommended in React. We suggest you to use a stateful approach where the page is re-rendered once a state is changed.

Let us consider for example a basic clock created using a function. We will see how to create a stateful solution that re-renders the page at each second.

Firstly, edit the src index.js file.

Before

import React from 'react';

import ReactDOM from 'react-dom';

function showTime()

{

const myElement = (

Welcome to clock

 

{new Date().toLocaleTimeString()}

);

ReactDOM.render(

myElement,

document.getElementById("root")

);

}

setInterval(showTime, 1000)

Edits:

import React from 'react';

import ReactDOM from 'react-dom';

class Clock extends React.Component {

}

We need to use a lifecycle function componentDidMount() to set an interval to update the state, and use componentWillUnmount() method to clear the interval and make the app efficient. This is how it is implemented.

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 (

<h1>Welcome to { this.props.title } !</h1>

<h2>{this.state.time.toLocaleTimeString()}</h2>

);

}

ReactDOM.render(

,

document.getElementById('root'));

It’s Quiz Time!

quiz-img
Did you find this article helpful?