0 votes
in ReactJS by

How to update a component every second?

1 Answer

0 votes
by

You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.

componentDidMount() {
  this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
}

componentWillUnmount() {
  clearInterval(this.interval)
}

Related questions

0 votes
asked Nov 26, 2019 in ReactJS by AdilsonLima
0 votes
asked Nov 3, 2023 in ReactJS by AdilsonLima
...