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;
2

There are 2 answers

0
Prateek Thapa On BEST ANSWER

If you're looking to make it short, rather than repeating the lines that gets currDate from toLocaleTimeString. You create a function that does that, and use it wherever you want.

EXAMPLE - 1

function getCurrDate() {
  return (new Date()).toLocaleTimeString()
}

const Clock = () => {
  const [currTime, updateTime] = useState(getCurrDate());

  return (
    <>
      <h1> {currTime}</h1>
      <button type="button" onClick={() => updateTime(getCurrDate())}>
        Updatetime
      </button>
    </>
  );
};

export default Clock;

EXAMPLE - 2

Store the recent date on the state and derive toLocaleTimeString() from it.

const Clock = () => {
  const [currTime, updateTime] = useState(new Date());

  return (
    <>
      <h1> {currTime.toLocaleTimeString()}</h1>
      <button type="button" onClick={() => updateTime(new Date())}>
        Updatetime
      </button>
    </>
  );
};

export default Clock;
0
Cijin Cherian On

Does something like this work for you?

  1 import React, { useState } from 'react';
  2 
  3 const getTime = () => {
  4   const date = new Date();
  5   const currDate = date.toLocaleTimeString();
  6 
  7   return currDate;
  8 };
  9 
 10 function Clock() {
 11   const [currTime, updateTime] = useState(getTime());
 12 
 13   const timeHandler = () => {
 14     updateTime(getTime());
 15   };
 16 
 17   return (
 18     <>
 19       <h1> {currTime}</h1>
 20       <button type="button" onClick={timeHandler}>
 21         Updatetime
 22       </button>
 23     </>
 24   );
 25 }
 26 
 27 export default Clock;