How can I declare currDate globally to use it in useState. The following code works just fine but wish to make it more efficient.
Is there any better way to shorten the code?
import React, { useState } from "react";
const Clock = () => {
const date = new Date();
const currDate = date.toLocaleTimeString();
const [currTime, updateTime] = useState(currDate);
console.log(currDate);
const timeHandler = () => {
console.log(1);
const date = new Date();
const currDate = date.toLocaleTimeString();
updateTime(currDate);
};
return (
<>
<h1> {currTime}</h1>
<button type="button" onClick={timeHandler}>
Updatetime
</button>
</>
);
};
export default Clock;
If you're looking to make it short, rather than repeating the lines that gets
currDate
fromtoLocaleTimeString
. You create a function that does that, and use it wherever you want.EXAMPLE - 1
EXAMPLE - 2
Store the recent date on the state and derive
toLocaleTimeString()
from it.