PASSWORD RESET

Your destination for complete Tech news

how to get the current date in React JS?

1.66K 0
< 1 min read

In ReactJS, you can get the current date using JavaScript’s built-in Date object. Here’s an example of how you can do this:

import React, { useState, useEffect } from 'react';

function App() {
  const [currentDate, setCurrentDate] = useState(new Date());

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentDate(new Date());
    }, 1000); // Update every second

    return () => clearInterval(interval); // Clean up the interval on unmount
  }, []);

  return (
    <div>
      <p>Current Date: {currentDate.toLocaleString()}</p>
    </div>
  );
}

export default App;

In this example, we’re using the useState hook to manage the state of the current date. We use the useEffect hook to set up an interval that updates the state every second using the setInterval function. The returned cleanup function from useEffect clears the interval when the component unmounts, preventing memory leaks.

The toLocaleString() method is used to format the currentDate as a human-readable string. You can adjust the formatting to your preference using other Date methods or third-party libraries like date-fns if needed.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.