react native show current time and update the seconds in real-time

inoutwhy picture inoutwhy · Dec 23, 2016 · Viewed 61.1k times · Source

I want to show the current time(MM/DD/YY hh:mm:ss) in react native app like a clock, and get update every seconds, I tried using new Date() and set it in state, but the time don't update unless I refresh the page. I also tried using setInterval function in render(), it do got update but it's expensive for CPU. is there a good method to realise the function?

state = {
    curTime: null,
}
render(){
    setInterval(function(){this.setState({curTime: new  Date().toLocaleString()});}.bind(this), 1000);
    return (
        <View>
            <Text style={headerStyle.marginBottom15}>Date: {this.state.curTime}</Text>
        </View>
    );
}

Answer

Nguy&#234;n Ho&#224;ng picture Nguyên Hoàng · Dec 23, 2016

Just move setInterval into componentDidMount function.

Like this :

  componentDidMount() {
    setInterval(() => {
      this.setState({
        curTime : new Date().toLocaleString()
      })
    }, 1000)
  }

This will change state and update every 1s.