Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get current date as a state in ReactJS

Introduction

Hello there! Have you ever wondered how you could display the current date on your website? Well, in this blog post, I'll be showing you how to get the current date as a state in ReactJS.

Let me first clarify what ReactJS is: it's a JavaScript library for creating user interfaces. Think of it as the 'V' in the MVC (Model View Controller) architecture. It handles the view part, i.e., what a user sees and interacts with on the web page.

Now, let's dive into the concept of 'state' in ReactJS. In simple terms, state is an object that stores property values that belong to a component. You can think of it as a storage box that holds the data we want to track and update.

Understanding Date Object in JavaScript

Before we dive into ReactJS, we need to understand the Date object in JavaScript. The Date object is a built-in object in JavaScript that stores the date and time. It can be created using the new Date() syntax.

Here's an example of how to create a Date object:

let currentDate = new Date();
console.log(currentDate);

In the console, you'll see the current date and time based on your system's local settings.

Setting up Your React Component

Now, let's move onto ReactJS. We'll create a simple functional component that displays the current date. A functional component is just a JavaScript function that takes props (short for properties) as an argument and returns a React element, which describes what should be rendered on the screen.

Here's a basic setup of our component:

import React from 'react';

function CurrentDate() {
  return (
    <div>
      <h1>Current Date</h1>
    </div>
  );
}

export default CurrentDate;

In this code, we have a functional component named CurrentDate that returns a div with an h1 tag.

Incorporating State Using the useState Hook

Now, we'll incorporate state into our component using the useState Hook. A Hook is a special function that lets you 'hook into' React features. Here, useState is a Hook that lets you add React state to your functional components.

Here’s how you declare a state variable in your component:

import React, { useState } from 'react';

function CurrentDate() {
  const [date, setDate] = useState(new Date());

  return (
    <div>
      <h1>Current Date: {date.toDateString()}</h1>
    </div>
  );
}

export default CurrentDate;

In this code, useState takes the current date as its initial state. The useState Hook returns an array with two values: the current state (date) and a function (setDate) that allows us to update the state. We're using array destructuring to assign names to these values.

The {date.toDateString()} in the h1 tag is a JavaScript expression that is being embedded in JSX (JavaScript XML). The toDateString() method converts the date to a more readable format.

Updating the Date

Now, what if we want our date to be updated every second? For this, we'll use another Hook called useEffect. useEffect lets you perform side effects in your functional components. It runs after every render, including the first render.

Here's how to use it:

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

function CurrentDate() {
  const [date, setDate] = useState(new Date());

  useEffect(() => {
    const timer = setInterval(() => {
      setDate(new Date());
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, []);

  return (
    <div>
      <h1>Current Date: {date.toDateString()}</h1>
    </div>
  );
}

export default CurrentDate;

In this code, we're using setInterval to update the date state every second (1000 milliseconds). The useEffect Hook takes two arguments: a function and an array of dependencies.

The function we passed to useEffect sets up a timer that updates the date state every second. The returned function from useEffect clears the interval when the component is unmounted or before it is re-rendered.

And voila! You now have a React component that displays the current date and updates it every second.

Conclusion

Getting the current date as a state in ReactJS might seem daunting, especially if you're new to programming. But I hope this post has helped you understand how to do it.

Remember, it's all about understanding the basics and then building upon them. ReactJS is a powerful library that can help you build dynamic and interactive user interfaces with ease. And the best part is, once you understand how to manipulate state and use Hooks, the possibilities are endless!

Happy coding!