Languages
[Edit]
EN

React - how to display current time with refresh

3 points
Created by:
Blessing-D
574

In this article, we would like to show you how to display current time which is refreshed after some short time in React.

In below example, we use interval with a React.useEffect hook to build a simple timer. 
We don't want unnecessary function calls with the useEffect hook so we use a reference to the function (created with a React.useRef hook). When setInterval performs some operations every specified time, it refers to the function currently assigned to the reference, updating the time stored as a state. The function assigned to the reference is updated every render cycle.
The whole mechanism will be stopped when a component is destroyed (with the clearInterval function).

Note: Go to the next section of this article to read more about useCurrentCallback function.

Runnable example:

// ONLINE-RUNNER:browser;

//Note: Uncomment import lines during working with JSX Compiler.
// import React from 'react';
// import ReactDOM from 'react-dom';

const useCurrentCallback = (callback) => {
  const reference = React.useRef();
  reference.current = callback;
  return (...args) => {
    return reference.current?.(...args);
  };
};

const App = () => {
  const [time, setTime] = React.useState(0);
  const currentCallback = useCurrentCallback(() => {
    const date = new Date();
    setTime(date.toISOString());
  });
  React.useEffect(() => {
    const handle = setInterval(currentCallback, 100);
    return () => clearInterval(handle);
  }, []);
  return (
    <div>{time}</div>
  );
};

const root = document.querySelector('#root');
ReactDOM.render(<App />, root);

useCurrentCallback

useCurrentCallback function uses React.useRef hook to initialize reference.current with a callback function that updates our time with a new date.

The useCurrentCallback returns an arrow function with an unspecified number of arguments (...args). The arrow function returns a callback function stored in reference.current with all of the ...args if possible, otherwise returns undefined. 

 

Note:
Read more about date and time formatting here.

Alternative titles

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

ReactJS

React - display current time with refresh
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join