Open In App

How to change state continuously after a certain amount of time in React?

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To change the state continuously allows us to repeatedly update the components state which can be used to implement counters, timers, and other time based components. In this article, we will see how to change state continuously after a certain amount of time in react.

Approach

To change state continuously after a certain time in React we will use JavaScript setInterval method. We will call the setState method inside setInterval to dynamically update the state.

setInterval method takes two parameter callback and time. The callback function is called again and again after that given amount of time.  Use the setState method to change the state of the component.

timing() {
setInterval(() => {
this.setState({
stateName: new-state-value
});
}, time);
}

Note: In case of React Functional Component we can use the useState hook.

Example 1: This example illustrates how to change the state continuously after a certain amount of time.

JavaScript
// Filename - App.js

import React, { Component } from "react";

class App extends Component {
	constructor(props) {
		super(props);
		this.state = { Number: 0 };
		this.makeTimer();
	}

	makeTimer() {
		setInterval(() => {
			let rand = Math.floor(Math.random() * 10) + 1;
			this.setState({ number: rand });
		}, 1000);
	}
	render() {
		return (
			<div>
				<h1>Random Number :{this.state.number}</h1>
			</div>
		);
	}
}

export default App;
JavaScript
// Filename - index.js

import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'

ReactDOM.render(<App />, document.querySelector('#root'))

Output: 


Next Article

Similar Reads