Home > Blockchain >  Update date now in React hook
Update date now in React hook

Time:07-18

I need to create a custom hook that updates the current time on click

export const useNow = (): [number, VoidFunction] => {
  const [now, setNow] = React.useState(Date.now())
  const update = () => {
    const newDate = new Date(now)
    setNow(Date.parse(newDate.getTime().toString()))
  }
  return [now, update]
}

The problem is that whenever the update method is invoked the now state is always updated with the same value.

How can I correctly set now with the current timestamp?

CodePudding user response:

The reason for now not updating is that new Date(now) creates a new date instance with the default state Date.now() that has been provided at the top of the component.

Creating a new Date() during update should resolve your problem.

import React from "react";

export const useNow = (): [number, VoidFunction] => {
  const [now, setNow] = React.useState<number>(new Date().getTime());

  const update = () => {
    setNow(new Date().getTime());
  };

  return [now, update];
};
  • Related