reactjsmernreactjs-fluxreact-fullstackreactjs-testutils

I am learning react and my code is working fine but how can i declare currDate single time to use it globally to use in useState


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;

Solution

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