Reputation: 55
I have created the functional component in React for time counter. Everything working fine. But, component is not re-rendering after every second. I am new in React.
So, how we can re-render the functional component with setInterval()
?
import React from 'react'
import withStyle from 'react-jss'
const counterStyle = {
counter:{
color:'#FFFFFF'
}
}
let date = new Date();
let todayDate = date.getDate();
let hours = date.getHours()
let minutes = date.getMinutes();
let second = date.getUTCSeconds();
const timerDisplay = () => {
date = new Date();
todayDate = date.getDate();
hours = date.getHours()
minutes = date.getMinutes();
second = date.getUTCSeconds();
}
const TimeCounter = ({classes}) => {
setInterval(() => {
timerDisplay()
}, 1000);
return(
<div className={classes.counter}>
<h1>{`${hours} : ${minutes} : ${second} : ${todayDate}`}</h1>
</div>
)
}
export default withStyle(counterStyle)(TimeCounter);
Upvotes: 4
Views: 3169
Reputation: 213
If you are new to ReactJS you should definitely take a look at the useState
documentation.
Your approach to a react component is wrong actually. To accomplish such simple task you can use state updates and React will automatically render the component. Without using library like momentjs, vanilla js component will look like this:
import React, { useState, useEffect } from 'react'
import withStyle from 'react-jss'
const TimeCounter = ({classes}) => {
const [time, setTime] = useState(new Date())
useEffect(() => {
setInterval(() => {
setTime(new Date())
}, 1000);
}, []);
return(
<div className={classes.counter}>
<h1>{`
${time.getHours()} :
${time.getMinutes()} :
${time.getUTCSeconds()} :
${time.getDate()}
`}</h1>
</div>
)
}
export default withStyle(counterStyle)(TimeCounter);
useState()
.setTime()
and re-render components using that state variable.Upvotes: 1
Reputation: 20755
You can use the useState
hook to store the date
,
const [timer, setTimer] = useState(new Date());
You must use the useEffect
hook to update the state in a interval,
useEffect(() => {
const interval = setInterval(() => {
console.log('This will run every second!');
setTimer(new Date());
}, 1000);
// This is important, you must clear your interval when component unmounts
return () => clearInterval(interval);
}, []) // [] is for to execute `useEffect` only once as `componentWillMount`
Upvotes: 1