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>
);
}
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.